【问题标题】:create flag based on row values in grep()根据 grep() 中的行值创建标志
【发布时间】:2018-06-07 17:22:02
【问题描述】:

我有一个 10 行的关于 potatoes 的推文数据框,需要根据每个 tweet 包含的标点符号(问号或感叹号)标记它们。 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

我也很乐意考虑比以grep 的输出为条件的更优雅的解决方案。任何帮助表示赞赏!

【问题讨论】:

    标签: r if-statement data-manipulation


    【解决方案1】:

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

    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]
    

    【讨论】:

    • 美丽 - 谢谢!编辑使答案更加有用/直观
    • 如果你已经使用了 tidyverse 函数,那么也可以考虑 stringr::str_detect 作为替代
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2020-03-31
    • 1970-01-01
    • 2019-10-12
    • 2020-12-26
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多