简体   繁体   English

通过添加新列来扩展data.frame

[英]Expand data.frame by adding new column

Here an example of my data.frame(s): 这是我的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? 如何使用df2观测值扩展df

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. 使用expand.grid的解决方案可为您提供两个变量的所有组合。

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 : 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 . lapplydf$x迭代,并将整个df2 cbinddf$x每个元素。 do.call combines everything together in one data.frame. do.call将所有内容组合到一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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