不确定为什么merge()没有水平合并所有行(在R中)

时间:2017-02-04 23:54:50

标签: r merge reshape2

我在R中有2个数据帧:

Item

我想通过“Crop”列合并它们,无论裁剪是出现在两个数据帧还是仅出现在其中一个数据帧中。如果0或NA仅出现在其中一个数据框中,则可以将其用作占位符。

ag<-structure(list(Crop = c("beans", "chayote", "chives", "chiwa squash", 
"cilantro", "corn", "epazote", "flower chiwa squash", "jicama", 
"macal", "onion", "papaya", "pineapple", "plantain", "red onion", 
"scallions", "solanum americanum ", "sugar cane", "sweet potato", 
"tomato", "yam", "yuca"), kg = c(21, 100, 26, 116, 2, 505, 0.05, 
4, 3, 29, 3, 14, 6.5, 407, 29, 10, 12, 99, 50, 68, 8, 121)), .Names = c("Crop", 
"kg"), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
11L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 22L, 23L, 24L), class = "data.frame")

ag1<-structure(list(Crop = c("agouti", "beans", "chayote", "chives", 
"chiwa squash", "cilantro", "corn", "epazote", "flower chiwa squash", 
"jicama", "llame", "macal", "mustard", "onion", "paca", "papaya", 
"pineapple", "plantain", "red onion", "scallions", "solanum americanum ", 
"sugar cane", "sweet potato", "tomato", "watermelon", "yam", 
"yuca"), kg = c(5, 25, 246.5, 50, 158, 303.83, 927, 0.35, 4, 
3, 8, 49, 1, 3, 34, 155, 7.5, 717, 318, 14, 17, 237, 98, 111.5, 
12, 25, 191)), .Names = c("Crop", "kg"), row.names = c(1L, 2L, 
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 16L, 17L, 
18L, 19L, 20L, 21L, 22L, 23L, 24L, 26L, 27L, 28L, 30L), class = "data.frame")

目标是使用一列作物名称的数据框,第二列使用kg来自ag,第三列使用kg来自ag1。但是,当我这样做时,它似乎是垂直合并而不是水平合并。最重要的是,并非所有行似乎都在合并。

merge(ag,ag1,all="TRUE")

我不确定为什么会这样。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:1)

也许这就是你想要的?

merge(x = ag,y = ag1,by = 'Crop',all = T)