Reproducible Sample Data
df <- data.frame(
change_time = c("[4605]", "[4000]", "[4305]",
"[5530]", "[6500]", "[5653]",
"[2936]", "[4691]", "[2500]")
)
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
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()
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.