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

问题描述 投票:0回答:1

这是我的代码:

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个回答
0
投票

使用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) 
© www.soinside.com 2019 - 2024. All rights reserved.