0
votes

Reproducible Sample Data

df <- data.frame(
  change_time = c("[4605]", "[4000]", "[4305]", 
                  "[5530]", "[6500]", "[5653]", 
                  "[2936]", "[4691]", "[2500]")
)

data frame with values

Hi, how do I change values to numeric? so far I've used as.numeric(), but I get the warning Warning message: NAs introduced by coercion

2
x <- c("[4605]", "[4000]");as.numeric(gsub("\\[|\\]", "", x)). Images are not a good way for posting data (or code). See this Meta and a relevant xkcd. Can you post sample data in dput format? Please edit the question with the code you've tried and with the output of dput(df). Or, if it is too big with the output of dput(head(df, 20)). (Note: df is the name of your dataset.) - Rui Barradas

2 Answers

0
votes

when dealing with R object, it is wise to use str() function to see what data types your are having. I'm not sure, but I'm assume that your data is a stringwith [ ] in each side.

 #Install from tidyverse or manually
library(magrittr)
library(stringr)
str_extract(df$change_time,"\\d*") %>% as.numeric()
0
votes

Here is a solution using the dplyr and stringr packages. mutate allows you to modify the existing change_time variable. str_remove_all is used to remove the matches pattern in the change_time variable. as.numeric converts the change_time variable from character to numeric.

Replace df with the name of your dataset.

# Recreate sample data 

df <- data.frame(
  change_time = c("[4605]", "[4000]", "[4305]", "[5530]", "[6500]", "[5653]", "[2936]", "[4691]", "[2500]")
)

# Import the libraries

library(dplyr)
library(stringr)

# Code to accomplish what is asked

df %>% 
  mutate(
    change_time = as.numeric(str_remove_all(change_time, "\\[|\\]"))
    )

# Output

#>   change_time
#> 1        4605
#> 2        4000
#> 3        4305
#> 4        5530
#> 5        6500
#> 6        5653
#> 7        2936
#> 8        4691
#> 9        2500

Created on 2021-03-11 by the reprex package (v0.3.0)