我有一个数据帧的列表。
dd <- list()
dd$data <- list(
ONE = data.frame(inAll = c(1.1,1.2,1.3), inAll_2 = c(1.4,1.5,1.6)),
TWO = data.frame(inAll = c(2.1,2.2,2.3), inAll_2 = c(2.4,2.5,2.6)),
THREE = data.frame(inAll = c(3.1,3.2,3.3), inAll_2 = c(3.4,3.5,3.6)),
FOUR = data.frame(inAll = c(4.1,4.2,4.3), inAll_2 = c(4.4,4.5,4.6)),
FIVE = data.frame(inAll = c(5.1,5.2,5.3), inAll_2 = c(5.4,5.5,5.6)),
SIX = data.frame(inAll = c(6.1,6.2,6.3), inAll_2 = c(6.4,6.5,6.6))
)
然后用后缀缩减这些数据帧
reduce(dd$data, full_join, by = "inAll", suffix = c("_x", "_y"))
我想要的输出是
map(dd$data, list())
但我希望这些名称与缩减后的数据集中的后缀相同。
我如何扩展这个映射函数,使我重命名列表中的列以反映缩减后的名称?
[我试着看了一下连接源码] 看起来所有匹配但没有连接的列都是:
请注意,在我的例子中,这些数据框架一般都有其他列,而且这些列的顺序并不总是相同的,所以我想避免任何脆弱的东西,比如通过索引匹配。
new_names <- function(df) {
# logic about new suffixes somehow
map(df,list())
}
一个看起来像这样的列表。
dd$data2 <- list(
ONE = data.frame(inAll = c(1.1,1.2,1.3), inAll_2_x = c(1.4,1.5,1.6)),
TWO = data.frame(inAll = c(2.1,2.2,2.3), inAll_2_y = c(2.4,2.5,2.6)),
THREE = data.frame(inAll = c(3.1,3.2,3.3), inAll_2_x_x = c(3.4,3.5,3.6)),
FOUR = data.frame(inAll = c(4.1,4.2,4.3), inAll_2_y_y = c(4.4,4.5,4.6)),
FIVE = data.frame(inAll = c(5.1,5.2,5.3), inAll_2_x_x_x = c(5.4,5.5,5.6)),
SIX = data.frame(inAll = c(6.1,6.2,6.3), inAll_2_y_y_y = c(6.4,6.5,6.6))
)
我们可以用 strrep
(自 base R
)为'x','y'。rep
绕过 list
列有 map2
和 rename_at
第二列 paste
(str_c
)的后缀通过
library(dplyr)
library(purrr)
library(stringr)
n <- ceiling(length(dd$data)/2)
map2(dd$data, strrep(rep(c('_x', '_y'), n), rep(seq_len(n), each = 2)), ~
{nm <- .y
.x %>%
rename_at(vars(inAll_2), ~ str_c(., nm))
})
#$ONE
# inAll inAll_2_x
#1 1.1 1.4
#2 1.2 1.5
#3 1.3 1.6
#$TWO
# inAll inAll_2_y
#1 2.1 2.4
#2 2.2 2.5
#3 2.3 2.6
#$THREE
# inAll inAll_2_x_x
#1 3.1 3.4
#2 3.2 3.5
#3 3.3 3.6
#$FOUR
# inAll inAll_2_y_y
#1 4.1 4.4
#2 4.2 4.5
#3 4.3 4.6
#$FIVE
# inAll inAll_2_x_x_x
#1 5.1 5.4
#2 5.2 5.5
#3 5.3 5.6
#$SIX
# inAll inAll_2_y_y_y
#1 6.1 6.4
#2 6.2 6.5
#3 6.3 6.6