Use lapply to go through a list of dataframes and change class of specific column

左心房为你撑大大i 提交于 2019-12-11 08:39:17

问题


I'm trying to go through a list that has two data frames and I want to change the class of column 2 from factor to data in each of those data frames. I can solve this with a for loop, but I want to learn how to do this with lapply.

tom <- data.frame(a = c(1,2,3), b = c("2017-01-09","2017-01-10","2017-09-11"))
kate <- data.frame(a = c(4,5,6), b = c("2017-01-09","2017-01-10","2017-09-11"))

testList <- list(tom,kate)

f <- lapply(testList, function(x) {
    x[,2] <- as.Date(x[,2])
})

I'm looking for f to return the original data frames but with the change in class for columns 2. Instead I get a list with only the dates (not the original data frames). Any thoughts?


回答1:


We need to return the 'x' or list element in 'f'

f <- lapply(testList, function(x) {
      x[,2] <- as.Date(x[,2])
      x
})

A more compact option without using the anonymous function call is transform

f1 <- lapply(testList, transform, b = as.Date(b))


来源:https://stackoverflow.com/questions/41581935/use-lapply-to-go-through-a-list-of-dataframes-and-change-class-of-specific-colum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!