我需要合并两个数据框。第一个看起来像这样:
> df1 <- data.frame(Artist = c("Vincent van ", "Vincent van ", "Theo van Gogh", "Alexandre", "Alexandre"), Location = c("a","a","a","b","c"), time = c(1,2,1,1,1))
> df1
Artist Location time
1 Vincent van a 1
2 Vincent van a 2
3 Theo van Gogh a 1
4 Alexandre b 1
5 Alexandre c 1
第二个:
> df2 <- data.frame(Artist = c("Vincent van Gogh", "Theo van Gogh", "Alexandre Dumas", "Alexandre Dumas"), HomeNumber = c(123,234,456,789), Location = c( "a","a","b","c"))
> df2
Artist HomeNumber Location
1 Vincent van Gogh 123 a
2 Theo van Gogh 234 a
3 Alexandre Dumas 456 b
4 Alexandre Dumas 789 c
我想要这个数据框:
> df3 <- data.frame(Artist = c("Vincent van ", "Vincent van ", "Theo van Gogh", "Alexandre", "Alexandre"), Location = c("a","a","a","b","c"), time = c(1,2,1,1,1), HomeNumber = c(123,123,234,456,789))
> df3
Artist Location time HomeNumber
1 Vincent van a 1 123
2 Vincent van a 2 123
3 Theo van Gogh a 1 234
4 Alexandre b 1 456
5 Alexandre c 1 789
>
合并仅适用于 Theo:
> df3 <- merge(df1, df2, by.x = "Artist", by.y = "Artist", all.x =TRUE)
> df3
Artist Location.x time HomeNumber Location.y
1 Alexandre b 1 NA <NA>
2 Alexandre c 1 NA <NA>
3 Theo van Gogh a 1 234 a
4 Vincent van a 1 NA <NA>
5 Vincent van a 2 NA <NA>
原因有两个: (a) 文森特在df1
. (b) 亚历山大是大仲马和大仲马的名字。
我可以用 处理(a)df1$Artist <- gsub("Vincent van $","Vincent van Gogh", df1$Artist)
,但我的数据实际上非常大,在执行之前gsub
我必须先知道文森特的全名。一种可能的解决方案是grep("Vincent van "...
在 df2 中使用,构建一个函数,如果结果向量的长度是1
我将使用gsub
返回df2$Artist
的 to df1
。我不知道该怎么做。
(b) 对我来说有点棘手。我能想到的一个解决方案(但不能编码)是首先使用一个if
函数从一个位置选择 Alexandre,然后使用 (a) 的解决方案来gsub
命名。
我认为解决 (a) 和 (b) 会返回我想要df3
的 . 你们知道如何有效地合并这些数据框吗?谢谢!
编辑:请注意,这Alexandre
实际上是两个不同的单位。因此,当合并两者时,应该有它们关联的 HomeNumber 和 Location。Vincent
是一个单一的单位,但在时间上有两个观察。