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
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.