我在一列中有一组单词,我想检查其中是否存在“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/