一个稍微不同的策略是没有匿名函数并[
直接调用。
fixDataFrames <- function(listOfDataFrames, columns = TRUE, drop = TRUE){
lapply(listOfDataFrames, `[`, , j = columns, drop = drop)
}
请注意,两者之间的空格,
很重要,因为它表示i
行索引的空间。通过留下这个缺失,我们得到与 相同的行为df[ , columns]
。我也将其设置drop = TRUE
为默认值,[
因此乐趣保持行为。
使用来自@Chase 答案的相同数据:
## Sample data
df1 <- df2 <- data.frame(x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10))
listOfDataFrames <- list(df1, df2)
fixDataFrames(listOfDataFrames)
fixDataFrames(listOfDataFrames, 2)
fixDataFrames(listOfDataFrames, 2, drop = FALSE)
给予
> fixDataFrames(listOfDataFrames)
[[1]]
x1 x2 x3
1 -1.98347150 -0.50473182 0.56554491
2 -0.19597580 0.41004825 -0.35646296
3 0.81792146 -0.07646175 -2.02534426
4 -0.01903514 0.70687248 -0.25373188
5 -0.49233958 0.42497338 -0.15647100
6 0.62296268 1.88127659 0.41952414
7 -0.27260248 -2.59046602 -1.99294060
8 1.46344557 1.44803287 0.08634971
9 0.62207040 1.78290849 -0.17131320
10 -1.05730518 -0.45478467 1.15346862
[[2]]
x1 x2 x3
1 -1.98347150 -0.50473182 0.56554491
2 -0.19597580 0.41004825 -0.35646296
3 0.81792146 -0.07646175 -2.02534426
4 -0.01903514 0.70687248 -0.25373188
5 -0.49233958 0.42497338 -0.15647100
6 0.62296268 1.88127659 0.41952414
7 -0.27260248 -2.59046602 -1.99294060
8 1.46344557 1.44803287 0.08634971
9 0.62207040 1.78290849 -0.17131320
10 -1.05730518 -0.45478467 1.15346862
> fixDataFrames(listOfDataFrames, 2)
[[1]]
[1] -0.50473182 0.41004825 -0.07646175 0.70687248 0.42497338 1.88127659
[7] -2.59046602 1.44803287 1.78290849 -0.45478467
[[2]]
[1] -0.50473182 0.41004825 -0.07646175 0.70687248 0.42497338 1.88127659
[7] -2.59046602 1.44803287 1.78290849 -0.45478467
> fixDataFrames(listOfDataFrames, 2, drop = FALSE)
[[1]]
x2
1 -0.50473182
2 0.41004825
3 -0.07646175
4 0.70687248
5 0.42497338
6 1.88127659
7 -2.59046602
8 1.44803287
9 1.78290849
10 -0.45478467
[[2]]
x2
1 -0.50473182
2 0.41004825
3 -0.07646175
4 0.70687248
5 0.42497338
6 1.88127659
7 -2.59046602
8 1.44803287
9 1.78290849
10 -0.45478467