【问题标题】:R remove "st", "nd", "rd", "th" from multiple columns in dataframeR从数据框中的多个列中删除“st”、“nd”、“rd”、“th”
【发布时间】:2019-02-27 01:57:50
【问题描述】:

我在第 1 列中有一个带有曲棍球队名称的数据框。在第 2-16 列中,统计类别排名(第 1、第 2、第 3、第 4 ......等等)。我想从所有类别中删除所有非数字金额,所以我只剩下 (1, 2, 3, 4...)

我知道我可以为每一列提供gsub("th", "", dataframe$column_name),但有没有办法在所有列中快速完成?

【问题讨论】:

    标签: r dplyr gsub stringr


    【解决方案1】:

    一个想法是使用mutate_at 将替换功能应用于您想要的列,如下所示。这里我提供了两个替换函数:str_replace 和 str_extract,它们都可以工作。 mutate_at、str_replace 和 str_extract 都来自 tidyverse 包。

    library(tidyverse)
    
    # Create an example data frame
    dat <- tibble(
      A = c("1st", "2nd", "3rd"),
      B = c("8th", "5th", "6th"),
      C = c("7th", "101st", "23rd"),
      Team = c("A", "B", "C")
    )
    
    # Solution 1: str_replace
    dat %>%
      mutate_at(vars(-Team), list(~as.integer(str_replace(., "st|nd|rd|th", ""))))
    # # A tibble: 3 x 4
    #       A     B     C Team 
    #   <int> <int> <int> <chr>
    # 1     1     8     7 A    
    # 2     2     5   101 B    
    # 3     3     6    23 C 
    
    # Solution 2: str_extract
    dat %>%
      mutate_at(vars(-Team), list(~as.integer(str_extract(., "[0-9]*"))))
    # # A tibble: 3 x 4
    #       A     B     C Team 
    #   <int> <int> <int> <chr>
    # 1     1     8     7 A    
    # 2     2     5   101 B    
    # 3     3     6    23 C
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多