gpt4 book ai didi

r - 使用数据框列表的公共(public)列创建数据框 - R

转载 作者:行者123 更新时间:2023-12-02 16:22:53 24 4
gpt4 key购买 nike

我需要获取在不同数据框中分隔的数据框列表的公共(public)列。请看下面的例子:

df1 <- data.frame(Dates = c('01-01-2020','02-01-2020','03-01-2020'), col1 = c(1,2,3), col2 = c(3,2,1))
df2 <- data.frame(Dates = c('01-01-2020','02-01-2020','03-01-2020'), col1 = c(4,5,6), col2 = c(6,5,4))
df3 <- data.frame(Dates = c('01-01-2020','02-01-2020'), col1 = c(7,8), col2 = c(8,7))
ldf <- list(df1, df2, df3)

所需的输出将是以下两个数据框:

df_col1:
Date df1 df2 df3
01-01-2020 1 4 7
02-01-2020 2 5 8
03-01-2020 3 6 NA

df_col2:
Date df1 df2 df3
01-01-2020 3 6 8
02-01-2020 2 5 7
03-01-2020 1 4 NA

当然,ldf 实际上要长得多,但列数固定为 5,因此输出数也固定为 (4)。这意味着我不介意为每个输出使用一个代码块。

我尝试了几种方法,但似乎都不起作用。我正在使用 base R,希望找到一个没有额外包的解决方案。

非常感谢您的宝贵时间!

最佳答案

我们使用 dplyr 中的 bind_rows 绑定(bind) list 元素,然后遍历“col”列以及常见的“Dates” , 使用 pivot_widerrename 如果需要 reshape 为“宽”格式

library(dplyr)
library(purrr)
library(tidyr)
library(stringr)
newdf <- bind_rows(ldf)
out <- map(names(newdf)[-1], ~
newdf %>%
select(Dates, .x) %>%
mutate(rn = rowid(Dates)) %>%
pivot_wider(names_from =rn, values_from = !! rlang::sym(.x)) %>%
rename_at(-1, ~ str_c('df', seq_along(.))))

-输出

out
#[[1]]
# A tibble: 3 x 4
# Dates df1 df2 df3
# <chr> <dbl> <dbl> <dbl>
#1 01-01-2020 1 4 7
#2 02-01-2020 2 5 8
#3 03-01-2020 3 6 NA

#[[2]]
# A tibble: 3 x 4
# Dates df1 df2 df3
# <chr> <dbl> <dbl> <dbl>
#1 01-01-2020 3 6 8
#2 02-01-2020 2 5 7
#3 03-01-2020 1 4 NA

或者使用base R

newdf <- do.call(rbind, ldf)
f1 <- function(dat, colName) {
lst1 <- split(dat[[colName]], dat$Dates)
do.call(rbind, lapply(lst1, `length<-`, max(lengths(lst1))))
}

f1(newdf, 'col1')
f1(newdf, 'col2')

关于r - 使用数据框列表的公共(public)列创建数据框 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65171449/

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