我有关于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
的输出更优雅的解决方案。任何帮助表示赞赏!
答案 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]