我写了一个简短的功能来清洁列表中的一些数据框。当使用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)
函数列_2产生所需的结果(清除了列表中的所有数据框(。列返回错误消息:
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.
问题是分配是在第一次运行后进行的,这里丢失了一些列。
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)