简体   繁体   中英

Changing the category of a variable in R: Warning message

I'm trying to change the participants' Age variable (in my dataset) that's showing as character (rather than numeric) using the following code..

bwdata6 <- bwdata6 %>% mutate(Age <- as.numeric(Age))

I get the following warning message when I run the code...

Warning messages: 1: Problem with mutate() input ..1. i NAs introduced by coercion
Input ..1 is Age <- as.numeric(Age). 2: In mask$eval_all_mutate(dots[[i]]) : 
  NAs introduced by coercion

Any ideas how to resolve this?

Without a warning you may use gsub .

d$x.num <- as.numeric(gsub("\\D", NA, d$x))

to identify those values that become NA accordingly, :

grep("\\D", d$x)
# [1] 2 4 6

d
#   x x.num
# 1 1     1
# 2 A    NA
# 3 2     2
# 4 B    NA
# 5 3     3
# 6 C    NA

Data:

d <- data.frame(x=c(1, "A", 2, "B", 3, "C"))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM