[英]Accessing grouping variables in purrr::map() with nested dataframes
[英]joining dataframe to nested dataframes within purrr::map_*
我的目标是将数据框与嵌套列表列中保存的数据框连接起来,例如:
data(mtcars)
library(tidyr)
library(purrr)
mtcars_nest <- mtcars %>% rownames_to_column() %>% rename(rowname_1 = rowname) %>% select(-mpg) %>% group_by(cyl) %>% nest()
mtcars_mpg <- mtcars %>% rownames_to_column() %>% rename(rowname_2 = rowname) %>% select(rowname_2, mpg)
join_df <- function(df_nest, df_other) {
df_all <- df_nest %>% inner_join(df_other, by = c("rowname_1" = "rowname_2"))
}
join_df <- mtcars_nest %>%
mutate(new_mpg = map_df(data, join_df(., mtcars_mpg)))
这将返回以下错误:
# Error in mutate_impl(.data, dots) : Evaluation error: `by` can't contain join column `rowname_1` which is missing from LHS.
因此,从嵌套输入接收的map_*
数据map_*
没有提供要加入rowname_1
的列名(即rowname_1
)。 我不知道为什么会这样。 我正在传递包含来自嵌套数据框的数据框的data
列。 我想要一个数据框输出,可以将其添加到输入嵌套数据框的新列中,例如
| rowname_1 | cyl | disp |...|mpg|
|:----------|:----|:-----|:--|:--|
几件事:
map*
的函数参数进行函数化(在purrr
); 和 map
而不是map_df
,尽管我无法确切找到为什么 map_df
无法正常工作的原因 ,但是我可以得到我认为没有它的期望行为。 次要点:
join_df()
分配给df_all
,并且它起作用的唯一原因是因为该分配无形地返回了您分配给df_all
; 我建议您应该明确:要么跟进return(df_all)
要么就不分配它,以inner_join(...)
结尾。 尝试这个:
library(tibble) # rownames_to_column
library(dplyr)
library(tidyr) # nest
library(purrr)
join_df <- function(df_nest, df_other) {
df_all <- inner_join(df_nest, df_other, by = c("rowname_1" = "rowname_2"))
return(df_all)
}
mtcars_nest %>%
mutate(new_mpg = map(data, ~ join_df(., mtcars_mpg)))
# # A tibble: 3 x 3
# cyl data new_mpg
# <dbl> <list> <list>
# 1 6. <tibble [7 x 10]> <tibble [7 x 11]>
# 2 4. <tibble [11 x 10]> <tibble [11 x 11]>
# 3 8. <tibble [14 x 10]> <tibble [14 x 11]>
new_mpg
实际上是data
列,其中包含另外一列。 由于我们知道我们具有完全冗余,因此您始终可以覆盖(或删除) data
:
mtcars_nest %>%
mutate(data = map(data, ~ join_df(., mtcars_mpg)))
# # A tibble: 3 x 2
# cyl data
# <dbl> <list>
# 1 6. <tibble [7 x 11]>
# 2 4. <tibble [11 x 11]>
# 3 8. <tibble [14 x 11]>
并获取嵌套的和现在增强的框架。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.