我写了一个简短的函数来清除列表中的某些数据框。当使用df [,1]方法选择列时,我的函数不起作用。但是,当我选择使用df $ Column时,它确实可以。为什么会这样?
columns_1 <- function(x) {
x[,1] <- dmy_hm(x[,1])
x[,2] <- NULL
x[,3] <- as.numeric(x[,3])
x[,4] <- NULL
return(x)
}
MS_ <- lapply(MS_, columns_1)
columns_2 <- function(x) {
x$DateTime <- dmy_hm(x$DateTime)
x$LogSeconds <- NULL
x$Pressure <- as.numeric(x$Pressure)
x$Temperature <- NULL
return(x)
}
MS_ <- lapply(MS_, columns_2)
columns_2函数产生所需的结果(列表中的所有数据框均已清除)。 columns_1返回错误消息:
Error in FUN(X[[i]], ...) :
(list) object cannot be coerced to type 'double'
In addition: Warning message:
All formats failed to parse. No formats found.
答案 0 :(得分:2)
问题在于分配是在第一次运行后执行的,这里有些列丢失了。
library(lubridate)
MS_ <- lapply(MS_, columns_1)
相反,可以通过分配给其他对象来完成
MS2_ <- lapply(MS_, columns_1)
set.seed(24)
df1 <- data.frame(DateTime = format(Sys.Date() + 1:5, "%d-%m-%Y %H:%M"),
LogSeconds = 1:5,
Pressure = rnorm(5), Temperature = rnorm(5, 25),
stringsAsFactors = FALSE)
MS_ <- list(df1, df1)