我正在使用与虹膜数据非常相似的数据帧:

data(iris)

df1 <- iris
df2 <- iris

df <- merge(df1, df2,  by = NULL)

head(df)


##    Petal.Width.x Species.x Sepal.Length.y Sepal.Width.y Petal.Length.y Petal.Width.y Species.y
##    0.2   setosa  5.1 3.5 1.4 0.2 setosa
##    0.2   setosa  5.1 3.5 1.4 0.2 setosa
##    0.2   setosa  5.1 3.5 1.4 0.2 setosa
##    0.2   setosa  5.1 3.5 1.4 0.2 setosa
##    0.2   setosa  5.1 3.5 1.4 0.2 setosa
##    0.4   setosa  5.1 3.5 1.4 0.2 setosa

我想要做的是将匹配的列名粘贴到同一列中 . 喜欢这里的物种:

df$Sepal.Width <- paste(df$Sepal.Width.x,df$Sepal.Width.y) 
df$Sepal.Width <- gsub(" ","/", df$Sepal.Width)

head(df)
## Species.x Sepal.Length.y Sepal.Width.y Petal.Length.y Petal.Width.y Species.y Species
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa
## setosa   5.1 3.5 1.4 0.2 setosa  setosa/setosa

但是,我试图将此代码应用于 I won't know the column names 的多个数据集,因此重复上述相同的代码将不起作用(即指定列) .

我认为这将是一个过程(我只是不确定如何在r中编码):

  • 粘贴到一列 only when the column names match . 这应该合并.x然后.y(所以我知道它们与哪个数据帧相关) .

  • 保留不匹配的列(即1列),但是,删除在步骤1中用于合并列的其余列

  • gsub到所需的格式

任何让我更接近解决方案的帮助(特别是当列名匹配时粘贴)将非常感激:)