这是我的代码:

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)

关于r - 从R中的sapply函数获取数据帧序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59254383/

10-12 16:30
查看更多