df<-data.frame(w=c("r","q"), x=c("a","b"))
y=c(1,2)
我应该如何将df和y合并为一个新的数据框,以包含来自df的所有行与来自y的元素的所有组合? 在此示例中,输出应为
data.frame(w=c("r","r","q","q"), x=c("a","a","b","b"),y=c(1,2,1,2))
w x y
1 r a 1
2 r a 2
3 q b 1
4 q b 2
df<-data.frame(w=c("r","q"), x=c("a","b"))
y=c(1,2)
data.frame(w=c("r","r","q","q"), x=c("a","a","b","b"),y=c(1,2,1,2))
w x y
1 r a 1
2 r a 2
3 q b 1
4 q b 2
dl <- unclass(df)
dl$y <- y
merge(df, expand.grid(dl))
# w x y
# 1 q b 1
# 2 q b 2
# 3 r a 1
# 4 r a 2
data.frame(lapply(df, rep, each = length(y)), y = y)
这应该可以工作
library(combinat)
df<-data.frame(w=c("r","q"), x=c("a","b"))
y=c("one", "two") #for generality
indices <- permn(seq_along(y))
combined <- NULL
for(i in indices){
current <- cbind(df, y=y[unlist(i)])
if(is.null(combined)){
combined <- current
} else {
combined <- rbind(combined, current)
}
}
print(combined)
这是输出结果:
w x y
1 r a one
2 q b two
3 r a two
4 q b one
... 或者让它更短 (并且不那么明显):
combined <- do.call(rbind, lapply(indices, function(i){cbind(df, y=y[unlist(i)])}))
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
然后,使用expand.grid
获取df
的所有行和y
的所有元素的组合的索引矩阵:
ind.mat = expand.grid(1:length(y), 1:nrow(df))
ind.mat
的行以获得结果:data.frame(t(apply(ind.mat, 1, function(x){c(as.character(df[x[2], ]), y[x[1]])})))