简体   繁体   中英

Expand data.frame by adding new column

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM