【问题标题】:Add new column with values depending on other columns添加新列,其值取决于其他列
【发布时间】:2020-11-24 11:24:52
【问题描述】:

我有一个数据框:

type                 value
message            Warning messages ID(34140)
eof                EOF within quoted string
message            Warning messages ID(4525)
message_error      Warning messages ID(4525) error
package            Attaching package: ‘jsonlite’
object             object in message 

我想添加列 type2,它的值取决于其他列的值。 该列的值必须是:

  1. “message_case”如果:
  • 列类型为“消息”

  • 列值中包含子字符串“警告消息 ID(”

  1. “eof_case”如果:
  • 列类型为“eof”

所以,想要的结果是:

type                 value                              type1
message            Warning messages ID(34140)        message_case
eof                EOF within quoted string            eof_case
message            Warning messages ID(4525)         message_case
message_error      Warning messages ID(4525) error      NA
package            Attaching package: ‘jsonlite’        NA 
object             object in message                    NA

我该怎么做?

【问题讨论】:

  • 我无法完全理解您想要什么。你能在你预期结果的每一行举一个例子吗?
  • 你试过用?grepl和朋友吗?
  • @markus 我虽然关于使用 stringi 但你看到它必须同时依赖于两列,我不知道该怎么做
  • @jhyeon 我添加了一些细节
  • 你试过这样的事情吗? type == "message" & grepl(...)@french_fries

标签: r string dataframe


【解决方案1】:

这行得通吗:

library(dplyr)
library(stringr)
df %>% mutate(type1 = case_when(type == 'message' & str_detect(value,'Warning messages ID') ~ 'message_case',
                                type == 'eof' ~ 'eof_case',
                                TRUE ~ NA_character_))
# A tibble: 6 x 3
  type          value                                 type1       
  <chr>         <chr>                                 <chr>       
1 message       "Warning messages ID(34140)"          message_case
2 eof           "EOF within quoted string"            eof_case    
3 message       "Warning messages ID(4525)"           message_case
4 message_error "Warning messages ID(4525) error"     NA          
5 package       "Attaching package: \x91jsonlite\x92" NA          
6 object        "object in message"                   NA      

【讨论】:

  • 出现:错误:mutate() 输入问题type1。 ✖ 正则表达式模式中的括号嵌套不正确。 (U_REGEX_MISMATCHED_PAREN) ℹ 输入 type1case_when(...)
  • @french_fries,试试 :str_detect(value,fixed('Warning messages ID'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多