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:
But it returns NA
s 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:
Why did I get NA
s 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