Ben
Ben

Reputation: 21705

How to combine a data frame and a vector

df<-data.frame(w=c("r","q"), x=c("a","b"))
y=c(1,2)

How do I combine df and y into a new data frame that has all combinations of rows from df with elements from y? In this example, the output should be

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

Upvotes: 4

Views: 391

Answers (4)

flodel
flodel

Reputation: 89107

data.frame(lapply(df, rep, each = length(y)), y = y)

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

This should do what you're trying to do, and without too much work.

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

Upvotes: 2

cogitovita
cogitovita

Reputation: 1745

First, convert class of columns from factor to character:

df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)

Then, use expand.grid to get a index matrix for all combinations of rows of df and elements of y:

ind.mat = expand.grid(1:length(y), 1:nrow(df))

Finally, loop through the rows of ind.mat to get the result:

data.frame(t(apply(ind.mat, 1, function(x){c(as.character(df[x[2], ]), y[x[1]])})))

Upvotes: 0

Boris Gorelik
Boris Gorelik

Reputation: 31817

this should work

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)

Here is the output:

      w x   y
    1 r a one
    2 q b two
    3 r a two
    4 q b one

... or to make it shorter (and less obvious):

combined <- do.call(rbind, lapply(indices, function(i){cbind(df, y=y[unlist(i)])}))

Upvotes: 0

Related Questions