【问题标题】:R iterate over group in R dataframe with for-loopR用for循环遍历R数据帧中的组
【发布时间】:2021-06-25 01:39:03
【问题描述】:

需要帮助。我有一个包含 3 列的数据框。

date <- c(2001:2015)
countries <- c("Afghanistan", "Afghanistan", "Afghanistan","Afghanistan", "Afghanistan", "Algeria", "Algeria", "Algeria", "Algeria", "Algeria", "Albania", "Albania", "Albania", "Albania", "Albania") 
value<- c(1:15)
df <- data.frame(date,country,value)

我想在每个独特的国家/地区应用一个函数prep_plot,并将输出一起添加到一个新的数据框中。我试过这样的for循环。

data <- data.frame()
for (country in unique(df$countries)){
 data1 <- prep_plot(country)
 data2 <- bind_rows(data, data1)
}

但是输出(data2)只有阿尔巴尼亚的数据。

【问题讨论】:

  • prep_plot 是做什么的?你也可以分享那个代码块吗?如果您在前几个国家/地区运行 prep_plot("Afghanistan") 并类似地运行,您能否确认它返回的是您的预期输出而不是空值?

标签: r for-loop tidyverse purrr


【解决方案1】:

你可以使用purrrmap_df

result <- purrr::map_df(unique(df$countries), prep_plot)

或者在基础 R 中:

result <- do.call(rbind, lapply(unique(df$countries), prep_plot))

【讨论】:

  • 可爱的罗纳克,谢谢。
【解决方案2】:

但是输出(data2)只有阿尔巴尼亚的数据。

您应该将data2 &lt;- bind_rows(data, data1) 替换为data2 &lt;- bind_rows(data2, data1)。也就是说,

data2 <- data.frame() # notice that this is changed as well
for (country in unique(df$countries)){
 data1 <- prep_plot(country)
 data2 <- bind_rows(data2, data1)
}

正如您当前所做的那样,data2 &lt;- bind_rows(data.frame(), data1) 只为您提供最后一个唯一国家/地区的数据(在您的情况下为 "Albania")。

正如其他人所提到的,基于lapplyrbind + do.callbind_rows 的解决方案可能会(快得多)(如Ronak 的answer)。

【讨论】:

  • 感谢本杰明指出我的错误。它现在适用于您的更正,但我将使用 Ronak 的答案。
【解决方案3】:

根据您的建议,以下应该可以工作,甚至不需要 data.frame。


library(dplyr)
countries %>% lapply( pred_plot ) %>% bind_rows


或者也许更清楚,以便您知道发生了什么:


## a list of all the pred_plot outputs:

l <- lapply( countries, pred_plot ) # this applies the function to each of the countries and returns a list with all the outputs

## combine these together with rbind:
data <- bind_rows( l )

这些语句可以像上面看到的那样链接起来,这种技术通常用于像这样的更简单的函数调用,其中链中一个链接的输出成为下一个函数的第一个参数,这就是 @987654323 @ 的全部内容。

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 2017-12-14
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2012-10-16
    相关资源
    最近更新 更多