代码之家  ›  专栏  ›  技术社区  ›  jo_

如果R中缺少字符,则重命名数据帧中的值

  •  0
  • jo_  · 技术社区  · 2 年前

    我有一个数据帧:

    example <- data.frame(
      Event = c('Negative_other 6',
                'Negative_other_7',
                'Neutral_self_1',
                'Negative_other_6',
                'Neutral_self 1',
                'Negative_other_7'),
      Type = c(1,2,2,1,2,2)
    )
    

    中的一些值 Event 标签不一致。例如,'Negative_other_6'和'Neutral_self_1'有时在'other'和数字之间有下划线,但有时没有。其他一些值的标签是一致的,比如'Negative_other_7'总是在'other'和数字之间有下划线。

    我想更新中的所有值 事件 使得在other和数字之间总是有下划线。

    这是所需的输出:

    solution <- data.frame(
      Event = c('Negative_other_6',
                'Negative_other_7',
                'Neutral_self_1',
                'Negative_other_6',
                'Neutral_self_1',
                'Negative_other_7'),
      Type = c(1,2,2,1,2,2)
    )
    

    有人知道这样做的有效方法吗?

    非常感谢。

    1 回复  |  直到 2 年前
        1
  •  0
  •   Onyambu    2 年前

    您可以使用 chatr (字符翻译自 ' ' _

    transform(example, Event = chartr(" ", "_", Event))
    
                 Event Type
    1 Negative_other_6    1
    2 Negative_other_7    2
    3   Neutral_self_1    2
    4 Negative_other_6    1
    5   Neutral_self_1    2
    6 Negative_other_7    2
    

    甚至 gsub 代替 “” _

    transform(example, Event = gsub(" ", "_", Event))
    
                 Event Type
    1 Negative_other_6    1
    2 Negative_other_7    2
    3   Neutral_self_1    2
    4 Negative_other_6    1
    5   Neutral_self_1    2
    6 Negative_other_7    2
    

    使用tidyverse:

    library(dplyr)
    example %>%
      mutate(Event = janitor::make_clean_names(Event))
                   Event Type
    1   negative_other_6    1
    2   negative_other_7    2
    3     neutral_self_1    2
    4 negative_other_6_2    1
    5   neutral_self_1_2    2
    6 negative_other_7_2    2
    
    推荐文章