【问题标题】:If Column Contains Text in Another Column, Add New Column With Indexed Text如果列在另一列中包含文本,则添加带有索引文本的新列
【发布时间】:2017-04-12 17:45:45
【问题描述】:

我有两个数据框:

第一个数据框:

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

谢谢!

【问题讨论】:

    标签: r join merge dplyr


    【解决方案1】:

    这对你有帮助吗?

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

    【讨论】:

      猜你喜欢
      • 2016-09-04
      • 1970-01-01
      • 2018-10-05
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多