Reputation: 185
Here an example of my data.frame(s):
df = data.frame(x=c(1871:1872))
df2 = data.frame(y=c(1:3))
How can I expand df
with df2
observations?
Desired output:
x y
1871 1
1871 2
1871 3
1872 1
1872 2
1872 3
I couldn't find any solution yet. Thanks
Upvotes: 1
Views: 579
Reputation: 24252
A third (but less elegant) solution:
data.frame(x=rep(df$x, each=nrow(df2)),
y=rep(df2$y,length(unique(df$x)))
)
# x y
# 1 1871 1
# 2 1871 2
# 3 1871 3
# 4 1872 1
# 5 1872 2
# 6 1872 3
Upvotes: 2
Reputation: 16121
A solution using expand.grid
that gives you all combinations of two variables.
df = data.frame(x=c(1871:1872))
df2 = data.frame(y=c(1:3))
expand.grid(x = df$x, y = df2$y)
# x y
# 1 1871 1
# 2 1872 1
# 3 1871 2
# 4 1872 2
# 5 1871 3
# 6 1872 3
Upvotes: 5
Reputation: 37879
One way with lapply
:
do.call(rbind, lapply(df$x, function(z) {
cbind(z, df2)
}))
# z y
#1 1871 1
#2 1871 2
#3 1871 3
#4 1872 1
#5 1872 2
#6 1872 3
lapply
iterates over df$x
and cbind
s the whole df2
to each element of df$x
. do.call
combines everything together in one data.frame.
Upvotes: 4