问题
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