EN VI

Coerce columns of data.frame from 'character' to "numeric" in R?

2024-03-16 17:00:04
How to Coerce columns of data.frame from 'character' to "numeric" in R

I am trying to coerce all the columns in a data frame as 'numeric' as a step previous to run lm() over it. One of the columns is read by R as a 'character', so I tried this:

df <- data_frame

for (i in colnames(df)){
  if (is.numeric(df[i]) == FALSE){
    df[i] == as.numeric(df[i])
  }
}

And I get this error:

Error in as.numeric(df[i]) : 'list' object cannot be coerced to type 'double'

Any ideas about what's happening?

Solution:

As @s_baldur states in his comment, you need double [[ to extract an item's list as a vector. [ merely subsets the original list, i.e., it returns a list:

> my_list <- list(X = c("A", "B"),
                  Y = 1:2,
                  Z = c(TRUE, FALSE))

> my_list[1]
$X
[1] "A" "B"

> class(my_list[1])
[1] "list"
> my_list[1:2]
$X
[1] "A" "B"

$Y
[1] 1 2

> class(my_list[1:2])
[1] "list"
> my_list[[1]]
[1] "A" "B"

> class(my_list[[1]])
[1] "character"
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login