【问题标题】:R - grepl look up for different strings and return 1 [duplicate]R - grepl 查找不同的字符串并返回 1 [重复]
【发布时间】:2019-07-26 08:41:13
【问题描述】:

我在 R 中使用 grep/grepl 函数时遇到问题。当我为多个字符串运行 grepl 时,我不知道如何生成所需的结果。

Text1 <- c("instance", "percentage", "n", 
          "instance percentage", "percentage instance")

ID <- c(1,2,3,4,5)

A <- c("A","B","C","D","E")

df <- data.frame(ID, Text1, A)

我想找到字符串实例或百分比(或两者兼而有之,并添加另一列“结果”并在每次找到时给出 1。

结果如下所示:

ID  Text1               A   Result
1   instance            A   1
2   percentage          B   1
3   n                   C   
4   instance percentage D   1
5   percentage instance E   1

【问题讨论】:

  • 试试grepl('instance|percentage', df$Text1)*1

标签: r


【解决方案1】:

使用grepl 查找所需字符串的存在并转换为整数。

df$Result <- as.integer(grepl("instance|percentage", df$Text1))

df
#  ID               Text1 A Result
#1  1            instance A      1
#2  2          percentage B      1
#3  3                   n C      0
#4  4 instance percentage D      1
#5  5 percentage instance E      1

【讨论】:

  • 谢谢。像魔术一样工作。如果我想添加一个条件,如果 A 包含到 B 中,结果应该为 0?
  • @Kalenji 你是说df$Result &lt;- as.integer(grepl("instance|percentage", df$Text1) &amp; df$A != "B") 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 2022-10-13
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多