gpt4 book ai didi

r - 使用 purrr::walk 从带有动态文件名的嵌套数据帧写入

转载 作者:行者123 更新时间:2023-12-01 13:20:34 26 4
gpt4 key购买 nike

我正在使用 purrr::map 将函数应用于嵌套数据框以获取新的数据框列表列。

现在我想使用来自同一行的列值作为文件名的一部分将这些新数据帧中的每一个写入文件。

我被困在如何提取其他列值以传递给文件名以写入文件。我有信心 purrr::walk应该涉及但如何访问列变量和列表数据框内容的方式是问题所在。

代表如下:

library(tibble) 
library(dplyr)
library(tidyr)
library(purrr)

# Data
data("mtcars")
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)

# Function to apply to nested dataframe
join_df <- function(df_nest, df_other) {
df_all <- inner_join(df_nest, df_other, by = c("rowname_1" = "rowname_2"))
return(df_all)
}

# 1. Apply function to `$data` to get new dataframe list column and add an extra 'case' column for filename
mtcars_nest %>%
mutate(case = c("first", "second", "third")) %>%
mutate(new_mpg = map(data, ~ join_df(., mtcars_mpg)))

# 2. Now write `$new_mpg` to file with filename sources from $cyl and $case
# I think `walk` is the correct to use but how to pass the two row values into filename?

## Not real code##
# mtcars_nest %>%
# walk(., function(x) {write.csv(., file = paste0(cyl, "_", case, ".csv")})

最佳答案

使用 pwalk :

... %>%
select(cyl, case, new_mpg) %>%
pwalk(~ write.csv(..3, file = paste0(..1, '_', ..2, '.csv')))

在您的代码之后链接:
mtcars_nest %>%
mutate(case = c("first", "second", "third")) %>%
mutate(new_mpg = map(data, ~ join_df(., mtcars_mpg))) %>%
select(cyl, case, new_mpg) %>%
pwalk(~ write.csv(..3, file = paste0(..1, '_', ..2, '.csv')))

关于r - 使用 purrr::walk 从带有动态文件名的嵌套数据帧写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com