r - 如何检查字符串中是否存在元音?并返回1或0?

标签 r string if-statement

我在一列中有一组单词,我想检查其中是否存在“o”或“u”。如果该单词有“o”或“u”,我想要一个带有“1”的新列,如果没有,我想要一个“0”。

数据现在的示例:

  ID    Word    
  1     rabbit 
  2     horse
  3     tunnel
  4     table

This is how I want the data to look:

ID    Word      Subset_Vowel
1     rabbit          0  
2     horse.          1
3     tunnel          1
4     table           0

我尝试了这段代码: DryRun_data_df$Subset_Vowel <- ifelse(str_detect(words, "o"|| "u"), 1, 0)

但是这里出现了错误: “o”错误|| “u”:“x ||”中的“x”类型无效y'

我也愿意接受其他方式来检查“o”和“u”是否存在/不存在

感谢您提前提供的所有帮助!!

最佳答案

|| 替换为 |,然后使用 as.integer(或 +)将逻辑强制转换为二进制>)

library(stringr)
df1$Subset_Vowel <- as.integer(str_detect(df1$Word, "o|u"))
df1
#  ID   Word Subset_Vowel
#1  1 rabbit            0
#2  2  horse            1
#3  3 tunnel            1
#4  4  table            0

或者在base R中使用grepl

df1$Subset_Vowel <- +(grepl("o|u", df1$Word))

数据

df1 <- structure(list(ID = 1:4, Word = c("rabbit", "horse", "tunnel", 
"table")), class = "data.frame", row.names = c(NA, -4L))

关于r - 如何检查字符串中是否存在元音?并返回1或0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62399129/

相关文章:

r - Ggplot2 方面 : put y-axis of the right hand side panel on the right side

java - 从字符串中删除大量字符的更简单方法?

c - 如何在 c 中正确使用 scandir()?

javascript - jQuery 如果不起作用?

r - 如何删除 R 中传单 map 中的归因

特定推文的转发计数

mysql - mysql中的多个ifs

python - 当 else 完成得最多时,制作 if-elif-elif-else 语句的最有效方法是什么?

r - 插入缺少日期/时间的行

arrays - 在 Struts 2 中将字符串数组作为静态参数传递