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
答案 0 :(得分: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
答案 1 :(得分:1)
data.frame(lapply(df, rep, each = length(y)), y = y)
答案 2 :(得分:0)
这应该有效
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)])}))
答案 3 :(得分:0)
首先,将列类从因子转换为字符:
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]])})))