【问题标题】:Get back sequence of dataframes from sapply function in R从 R 中的 sapply 函数取回数据帧序列
【发布时间】:2019-12-09 18:07:47
【问题描述】:

这是我的代码:

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

我该如何解决?

【问题讨论】:

    标签: r dataframe sapply


    【解决方案1】:

    使用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) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多