从 R 中的 sapply 函数获取数据帧序列



这是我的代码:

test_df <- data.frame(col_1 = seq(1,5), col_2 = seq(1,5))
test_function <- function(var_1 = NA, test_df = NA){
test_df$col_1 <- test_df$col_1 + var_1
return(test_df)
}
sapply_result <-sapply(seq(7,9), test_function, test_df = test_df) 

我希望从中得到 3 个数据帧,其中每个数据帧看起来像原始数据帧test_df,但col_1按序列的元素递增。

这是我实际得到的:

[,1]      [,2]      [,3]     
col_1 Integer,5 Integer,5 Integer,5
col_2 Integer,5 Integer,5 Integer,5

我该如何解决?

对于sapply,默认选项是simplify = TRUE,它会这样做。 相反,我们可以使用lapply始终返回list

lapply(seq(7,9), test_function, test_df = test_df)

或者利用simplify = FALSE

sapply(seq(7,9), test_function, test_df = test_df, simplify = FALSE) 

最新更新