如果列包含另一列中的文本,请添加带索引文本的新列

时间:2016-11-28 21:31:58

标签: r join merge dplyr

我有两个数据帧:

1st Dataframe:

Placement <- c('B-dghealpha', 'B-deAlpha', 'B-edfBeta', 'B-edgesg', 'B-edghe',
'B-polard', 'B-plotter', 'C-wertw', 'OPLTWE', 'optional')

This_Month <- c(2000,4000,4000,5000,5400,9000,1222,1424,2222,1908)

Last_Month <- c(21000, 23400, 26800, 1234, 1245, 4593, 4958, 1223, 1111, 2222)

df1 <- data.frame(Placement, This_Month, Last_Month)

df1

     Placement This_Month Last_Month
1  B-dghealpha       2000      21000
2    B-deAlpha       4000      23400
3    B-edfBeta       4000      26800
4     B-edgesg       5000       1234
5      B-edghe       5400       1245
6     B-polard       9000       4593
7    B-plotter       1222       4958
8      C-wertw       1424       1223
9       OPLTWE       2222       1111
10    optional       1908       2222

第二个数据帧:

Family <- c('ALPHA', 'BETA', 'PLOT', 'OPTION')

df2<-as.data.frame(Family)

df2

  Family
1  ALPHA
2   BETA
3   PLOT
4 OPTION

如何在名为Family的df1中添加另一列,其中df2中的值与df1的放置列中包含的文本匹配?

需要最终产出:

     Placement This_Month Last_Month Family
1  B-dghealpha       2000      21000  ALPHA
2    B-deAlpha       4000      23400  ALPHA
3    B-edfBeta       4000      26800   BETA
4     B-edgesg       5000       1234     NA
5      B-edghe       5400       1245     NA
6     B-polard       9000       4593     NA
7    B-plotter       1222       4958   PLOT
8      C-wertw       1424       1223     NA
9       OPLTWE       2222       1111     NA
10    optional       1908       2222 OPTION

谢谢!

1 个答案:

答案 0 :(得分:2)

这对你有帮助吗?

df1$Family = NA_character_
p = tolower(Placement)
f = tolower(Family)
sapply(seq_along(f),function(i) df1$Family[grepl(f[i],p)] <<- Family[i])