基于grep()中的行值创建标志
我有一个关于土豆的10行推文数据框,需要根据每个推文包含的标点(问号或感叹号)标记它们。基于grep()中的行值创建标志,r,if-statement,data-manipulation,R,If Statement,Data Manipulation,我有一个关于土豆的10行推文数据框,需要根据每个推文包含的标点(问号或感叹号)标记它们。grep函数将返回出现以下字符的行号: grep("\\?", potatoes$tweet) grep("!", potatoes$tweet) 我已经尝试在dplyr中使用mutate创建标志变量question,如图所示 potatoes$question <- NA potatoes <- mutate(potatoes, question = +row_number(grep("\\?
grep
函数将返回出现以下字符的行号:
grep("\\?", potatoes$tweet)
grep("!", potatoes$tweet)
我已经尝试在dplyr中使用mutate
创建标志变量question
,如图所示
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
grepgrepl
而不是grep
,因为grep
返回匹配发生的索引/位置,而grepl
返回逻辑向量,其中TRUE表示匹配元素,FALSE表示不匹配。它可以用作旗帜
i1 <- grepl("!", potatoes$tweet)
漂亮-谢谢!如果你已经使用了TydError函数,那么编辑也会使答案更有用/直观。
potatoes$question <- i1 * seq_len(nrow(potatoes$sweet))
i2 <- grep("!", potatoes$tweet)
potatoes$question[i2] <- seq_len(nrow(potatoes))[i2]