R 通过行/列名在第三维上连接数据帧
我有任意数量的数据帧,包括行和列名 我的目标是使用行/列名作为连接键,在三维上连接这些数据帧,即,我希望结果是一个命名的三维数组 我的问题是我不想在位置上加入它们,而是通过它们的行/列名 我知道我可以使用abind()沿任何所需维度连接数组,但abind按位置连接数据,而不是按dimname连接数据 在sql术语中,我想要使用行/列名作为连接键的完全连接,但要沿着第三个维度 这里有一个只有两个数据帧的小型可复制示例:R 通过行/列名在第三维上连接数据帧,r,R,我有任意数量的数据帧,包括行和列名 我的目标是使用行/列名作为连接键,在三维上连接这些数据帧,即,我希望结果是一个命名的三维数组 我的问题是我不想在位置上加入它们,而是通过它们的行/列名 我知道我可以使用abind()沿任何所需维度连接数组,但abind按位置连接数据,而不是按dimname连接数据 在sql术语中,我想要使用行/列名作为连接键的完全连接,但要沿着第三个维度 这里有一个只有两个数据帧的小型可复制示例: first <- data.frame(one=c(1,2), two=
first <- data.frame(one=c(1,2), two=c(3,4), row.names = c("one", "two"))
second <- data.frame(one=c(10,20), three=c(50,60), row.names = c("one", "three"))
result <- someMagicFunction(first, second)
首先不清楚“数组”的事情。我会这样解决它:
如果您正在寻找快速、基本且优雅的解决方案:
数据:
使用数组
有什么特别的原因吗?我的意思是,在列和行名称上进行连接是很不寻常的,或者?为什么不重新排列行/列,使它们处于适当的顺序,然后使用abind
?
result <- array(data=c(1, 2, NA, 3, 4, NA, NA, NA, NA,
10, NA, 20, NA, NA, NA, 50, NA, 60),
dim = c(3, 3, 2),
dimnames = list(
c("one", "two", "three"),
c("one", "two", "three"),
c("first", "second")))
> result
, , first
one two three
one 1 3 NA
two 2 4 NA
three NA NA NA
, , second
one two three
one 10 NA 50
two NA NA NA
three 20 NA 60
library(abind)
library(magrittr)
in.dfs <- list(first, second)
cols <- unique(unlist(lapply(in.dfs, names)))
rows <- unique(unlist(lapply(in.dfs, rownames)))
allNA <-
matrix(NA, length(cols), length(rows)) %>%
`colnames<-`(cols) %>%
`rownames<-`(rows)
lapply(in.dfs, function(df){
allNA[rownames(df), names(df)] <- as.matrix(df)
allNA
}) %>%
list(along = 3) %>%
do.call(what = abind)
# , , 1
#
# one two three
# one 1 3 NA
# two 2 4 NA
# three NA NA NA
#
# , , 2
#
# one two three
# one 10 NA 50
# two NA NA NA
# three 20 NA 60
first <- data.frame(one=c(1,2), two=c(3,4), row.names = c("one", "two"))
second <- data.frame(one=c(10,20), three=c(50,60), row.names = c("one", "three"))
l <- list(first, second)
dn <- unique(c(sapply(l, names)))
model<-as.data.frame(structure(rep(NA,length(dn)^2), .Dim = c(length(dn), length(dn)), .Dimnames = list(dn, dn)))
lapply(l, function(el){model[names(el),names(el)] <- el;model})
[[1]]
one two three
one 1 3 NA
two 2 4 NA
three NA NA NA
[[2]]
one two three
one 10 NA 50
two NA NA NA
three 20 NA 60