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])
Charles Stangor
  • 292
  • 7
  • 21

3 Answers3

3

We can use lapply to loop over the columns of interest and convert to numeric

 df[1:2] <- lapply(df[1:2], as.numeric)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

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
Community
  • 1
  • 1
Worice
  • 3,847
  • 3
  • 28
  • 49
0

You can use matrix indexing without any hidden loops:

df[, 1:2] <- as.numeric(as.matrix(df[, 1:2]))
jogo
  • 12,469
  • 11
  • 37
  • 42