Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dataframe - Convert multiple columns from factor to numeric but obtaining NAs in R

Assuming the following dataframe df:

df <- structure(list(`week1` = structure(c(number = 4L, 
area1 = 1L, area2 = 2L, price1 = 3L, 
price2 = 5L), .Label = c("154.93", "304.69", "3554.50", 
"49", "7587.22"), class = "factor"), `week2` = structure(c(number = 3L, 
area1 = 1L, area2 = 4L, price1 = 2L, 
price2 = 5L), .Label = c("28.12", "2882.91", "30", 
"44.24", "4534.47"), class = "factor")), class = "data.frame", row.names = c("number", 
"area1", "area2", "price1", 
"price2"))

I'm try to convert its week1 and week2 columns from factor to numeric with:

cols = c(1, 2)
df[, cols] <- as.numeric(as.character(df[, cols]))
# df[cols] <- lapply(df[cols], as.numeric) # gives incorrect results

Out:

enter image description here

But it returns NAs or incorrect results for those columns. However, the following code gives right answer:

cols = c(1, 2)   
df[, cols] = apply(df[, cols], 2, function(x) as.numeric(as.character(x)))
df 

Out:

enter image description here

Why did I get NAs with the first solution which works for this case? Thanks.

question from:https://stackoverflow.com/questions/65840013/convert-multiple-columns-from-factor-to-numeric-but-obtaining-nas-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

as.character/as.numeric expects a vector as input. With df[, cols] you are passing a dataframe to it (check class(df[, cols])).

If you are talking about the accepted answer in the link it says to change the code in for loop and doesn't suggest to pass entire dataframe. To change class of multiple columns you can use for loop, apply or lapply.

df[cols] <- lapply(df[cols], function(x) as.numeric(as.character(x)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...