简体   繁体   中英

Data frame not getting converted to numeric

I have 100 files in a list which I would access using:

my.data[[1]], my.data[[2]] ... my.data[[100]]

each of these is a data.frame containing 202 columns and 2080 rows and I would like to convert them to numeric class. I tried with:

for (i in 1:100) {
  my.data[[i]] <- sapply(my.data[[i]], as.numeric)
}

but when I check the class after running this loop using:

class(my.data[[1]])

I get the class as "matrix".

Of course, I tried to check them with one of the data.frames before looping; that too gave me the same result.

Please help. Where I could possibly be wrong?

Try:

  set.seed(49)
  my.data <- lapply(1:5, function(x) as.data.frame(matrix(as.character(sample(20,5*6,replace=TRUE)), ncol=6),stringsAsFactors=F))
  my.data[] <- lapply(my.data, function(x) {x[] <-lapply(x, as.numeric);x})
  str(my.data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM