简体   繁体   English

添加具有取决于其他列的值的新列

[英]Add new column with values depending on other columns

I have a dataframe:我有一个数据框:

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 

I want to add column type2 which has values depending on other columns values.我想添加具有取决于其他列值的值的列 type2。 The value on that column must be:该列上的值必须是:

  1. "message_case" if: "message_case" 如果:
  • column type is "message"列类型是“消息”

  • column value has substring "Warning messages ID(" in it列值具有子字符串“警告消息 ID(”)

  1. "eof_case" if: “eof_case”如果:
  • column type is "eof"列类型是“eof”

So, desired result is:所以,想要的结果是:

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

How could i do that?我怎么能那样做?

Does this work:这是否有效:

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      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM