根据grep()中的行值创建标志

时间:2018-06-07 17:22:03

标签: r if-statement grep data-manipulation

我有关于potatoes的推文的10行数据框,需要根据每个tweet包含的标点符号(问号或感叹号)标记它们。 grep函数将返回显示这些字符的行号:

grep("\\?", potatoes$tweet)
grep("!", potatoes$tweet)

我已尝试在dplyr中使用question创建标记变量mutate,如图所示...

potatoes$question <- NA
potatoes <- mutate(potatoes, question = +row_number(grep("\\?", potatoes$tweet)))

Error in mutate_impl(.data, dots) : 
Column `question` must be length 10 (the number of rows) or one, not 3

我也很高兴考虑比grep的输出更优雅的解决方案。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

我们可以使用grepl代替grep,因为grep返回匹配发生的索引/位置,而grepl返回逻辑vector,其中TRUE表示匹配元素,FALSE不匹配。它可以用作标志

i1 <- grepl("!", potatoes$tweet)

如果我们需要更改为行号,

potatoes$question <- i1 * seq_len(nrow(potatoes$sweet))

类似地,带有行索引的grep可用于赋值

i2 <- grep("!", potatoes$tweet)
potatoes$question[i2] <- seq_len(nrow(potatoes))[i2]