我们可以通过使用 lapply 循环遍历 list 然后将 trimws 与 lapply 按列应用来简化它(因为 trimws 是矢量化的)
df_list1 <- lapply(df_list, function(dat) {
dat[] <- lapply(dat, trimws)
dat
})
通过j in i和z in j,假设list的length与每个数据集的列数和行数相同,可能不是大小写,从而导致下标越界错误。
根据以下示例数据,length 为 10,但nrow 和ncol 小于该值,导致下标错误
for(i in 1:length(df_list)){
for (j in i) {
for(z in j){
df_list[[i]][[j]][[z]] <-
trimws(df_list[[i]][[j]][[z]])
}
}
}
.subset2(x, i, exact = exact) 中的错误:下标超出范围
数据
df_list <- list(structure(list(col1 = c("a ", "b", "c "), col2 = c("b ",
"d", "f")), class = "data.frame", row.names = c(NA, -3L)), structure(list(
col1 = c("a ", "b", "c ", "d"), col2 = c("b ", "d", "f",
"g "), col3 = c(" f", "d", "m ", "c")), class = "data.frame", row.names = c(NA,
-4L)), structure(list(col1 = c("a ", "b", "c "), col2 = c("b ",
"d", "f")), class = "data.frame", row.names = c(NA, -3L)), structure(list(
col1 = c("a ", "b", "c ", "d"), col2 = c("b ", "d", "f",
"g "), col3 = c(" f", "d", "m ", "c")), class = "data.frame", row.names = c(NA,
-4L)), structure(list(col1 = c("a ", "b", "c "), col2 = c("b ",
"d", "f")), class = "data.frame", row.names = c(NA, -3L)), structure(list(
col1 = c("a ", "b", "c ", "d"), col2 = c("b ", "d", "f",
"g "), col3 = c(" f", "d", "m ", "c")), class = "data.frame", row.names = c(NA,
-4L)), structure(list(col1 = c("a ", "b", "c "), col2 = c("b ",
"d", "f")), class = "data.frame", row.names = c(NA, -3L)), structure(list(
col1 = c("a ", "b", "c ", "d"), col2 = c("b ", "d", "f",
"g "), col3 = c(" f", "d", "m ", "c")), class = "data.frame", row.names = c(NA,
-4L)), structure(list(col1 = c("a ", "b", "c "), col2 = c("b ",
"d", "f")), class = "data.frame", row.names = c(NA, -3L)), structure(list(
col1 = c("a ", "b", "c ", "d"), col2 = c("b ", "d", "f",
"g "), col3 = c(" f", "d", "m ", "c")), class = "data.frame", row.names = c(NA,
-4L)))