2013-09-29 47 views
3
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 

回答

1
data.frame(lapply(df, rep, each = length(y)), y = y) 
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)])})) 
0

首先,转换类colu MNS从因子到字符:

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]])}))) 
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