How can I convert columns 1 and 2 to numeric? I tried this which seemed obvious to me, but wasn't.
Thanks
df <- data.frame(v1 = c(1,2,'x',4,5,6), v2 = c(1,2,'x',4,5,6), v3 = c(1,2,3,4,5,6), stringsAsFactors = FALSE)
as.numeric(df[,1:2])
How can I convert columns 1 and 2 to numeric? I tried this which seemed obvious to me, but wasn't.
Thanks
df <- data.frame(v1 = c(1,2,'x',4,5,6), v2 = c(1,2,'x',4,5,6), v3 = c(1,2,3,4,5,6), stringsAsFactors = FALSE)
as.numeric(df[,1:2])
We can use lapply
to loop over the columns of interest and convert to numeric
df[1:2] <- lapply(df[1:2], as.numeric)
I suggest this approach, using unlist
. I particularly like the "one line" approach, when possible.And for more options and references, I strongly suggest this beautiful post.
df <- data.frame(v1 = c(1,2,'x',4,5,6), v2 = c(1,2,'x',4,5,6),
v3 = (1,2,3,4,5,6), stringsAsFactors = FALSE)
df[, c("v1","v2")] <- as.numeric(as.character(unlist(df[, c("v1","v2")])))
Warning message:
NAs introduced by coercion
str(df)
data.frame': 6 obs. of 3 variables:
$ v1: num 1 2 NA 4 5 6
$ v2: num 1 2 NA 4 5 6
$ v3: num 1 2 3 4 5 6
You can use matrix indexing without any hidden loops:
df[, 1:2] <- as.numeric(as.matrix(df[, 1:2]))