-1

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?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
DrZaheer
  • 23
  • 5
  • 1
    That means that at least one of your values is not very numeric looking. You can find the problematic values using the answers here: https://stackoverflow.com/questions/21196106/finding-non-numeric-data-in-an-r-data-frame-or-vector – MrFlick Dec 24 '20 at 20:50
  • `mutate` doesn't use `<-` assignments, it uses `=` to attach values to arguments. – user2554330 Dec 24 '20 at 20:58
  • I checked the link, how do I apply the code to my dataset to figure which values are probllematic? The code is as follows: which.nonnum <- function(x) { Age <- is.na(suppressWarnings(as.numeric(as.character(x)))) which(Age & !is.na(x)) – DrZaheer Dec 24 '20 at 21:05
  • @user2554330 so just changing <- to = should solve the problem? I just tried it (i.e., Age = as.numeric (Age)), it didn't work! – DrZaheer Dec 24 '20 at 21:08
  • Please make it easier for people who are trying to help you. Provide a reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Dec 25 '20 at 03:24
  • Thanks for the link Ronak, next time I'll try to make my questions more easier to interpret. – DrZaheer Dec 27 '20 at 15:25

1 Answers1

0

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"))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • So applying gsub to my data do I run the following code... d$x.num <- as.numeric(gsub("\\Age", NA, d$x)) – DrZaheer Dec 24 '20 at 21:24
  • 1
    @DrZaheer `as.numeric(gsub("\\D", NA, d$Age))`, the `"\\D"` is a regular expression for "any non-digit", read `?gsub` and `?"regular expression"`. – jay.sf Dec 24 '20 at 21:28