Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading