简体   繁体   English

使用lapply将函数应用于多个数据集

[英]Apply a function to multiple datasets using lapply

I have a large number of datasets for which I want to create the same variable. 我有大量的数据集,我想为其创建相同的变量。 I would like to create a function to avoid having to repeat the same code many times. 我想创建一个函数,以避免多次重复相同的代码。

I tried the code below: the first 3 lines describe the creation of the variable that I am trying to apply through the function created below. 我尝试了下面的代码:前3行描述了我试图通过下面创建的函数应用的变量的创建。

data1 <- data1 %>%
  dplyr::group_by(id)%>%
  dplyr::mutate(new_var = sum(score))


list_data <- c(data1, data2, data3)
my_func <- function(x) {
  x <- x %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(new_var = sum(score))
}

lapply(list_data, my_func)

I obtain the error message 我收到了错误消息

no applicable method for 'group_by' applied to an object of class "character". 没有适用于'group_by'的方法应用于类“character”的对象。

Could you please help me figure this out? 你能帮我搞清楚吗?

for me this works fine: 对我来说这很好:

my_func <- function(x) {
  x <- x %>%
    dplyr::group_by(id) %>%
    dplyr::mutate(new_var = sum(score))
}
data1 <- data.frame(id = rep(1:3, each = 3), score = 1:9)
data2 <- data.frame(id = rep(1:3, each = 3), score = 11:19)
data3 <- data.frame(id = rep(1:3, each = 3), score = 21:29)


list_data <- list(data1, data2, data3)
lapply(list_data, my_func)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM