【问题标题】:Combining Two Data Frames Horizontally in R在R中水平组合两个数据框
【发布时间】:2019-07-17 05:26:11
【问题描述】:

我想在 R 中水平合并两个数据框。

这是我的两个数据框:

数据框 1:

veg     loc    quantity 

carrot  sak    three
pepper  lon    two
tomato  apw    five

数据框 2:

seller   quantity  veg

Ben      eleven    eggplant  
Nour     six       potato
Loni     four      zucchini
Ahmed    two       broccoli

我希望结果是一个如下所示的数据框:

veg       quantity

carrot    three
pepper    two
tomato    five
eggplant  eleven
potato    six
zucchini  four
broccoli  two

【问题讨论】:

标签: r


【解决方案1】:

问题说“水平”,但从示例输出来看,您的意思似乎是“垂直”。

现在,假设在最后的注释中可重现地显示输入,rbind 他们就像这样。不使用任何包,也不覆盖任何对象。

sel <- c("veg", "quantity")
rbind( df1[sel], df2[sel] )

如果您愿意,可以将第一行代码替换为以下代码,该代码会挑选出与sel 相同结果的公共列。

sel <- intersect(names(df1), names(df2))

注意

Lines1 <- "veg     loc    quantity 
carrot  sak    three
pepper  lon    two
tomato  apw    five"

Lines2 <- "seller   quantity  veg
Ben      eleven    eggplant  
Nour     six       potato
Loni     four      zucchini
Ahmed    two       broccoli"

df1 <- read.table(text = Lines1, header = TRUE, strip.white = TRUE)
df2 <- read.table(text = Lines2, header = TRUE, strip.white = TRUE)

【讨论】:

    【解决方案2】:

    你可以这样做:

    library (tidyverse)
    
    df1 <- df1%>%select(veg, quantity)
    df2 <- df2%>%select(veg, quantity)
    
    df3 <- rbind(df1, df2)
    
    

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 2020-10-05
      • 1970-01-01
      • 2018-10-12
      • 2023-04-04
      • 2015-04-22
      • 2023-03-06
      相关资源
      最近更新 更多