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

Get back sequence of dataframes from sapply function in R

这是我的代码:

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 来始终 return a 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)