【问题标题】:Chop off the first letter of every variable name [duplicate]切掉每个变量名的第一个字母[重复]
【发布时间】:2019-10-25 12:28:24
【问题描述】:

我有一些看起来像这样的数据:

    country agdp apop
1        US  100  100
2 Australia   50   50

变量名是agdpapop,但我希望它们是gdppop。我的真实数据有很多很多变量都需要这种转换。

这就是我想要的结果:

 country gdp pop
1        US  100  100
2 Australia   50   50

下面的可重现代码:

df <- data.frame(stringsAsFactors=FALSE,
     country = c("US", "Australia"),
        agdp = c(100, 50),
        apop = c(100, 50)

desired_df <- data.frame(stringsAsFactors=FALSE,
     country = c("US", "Australia"),
        gdp = c(100, 50),
        pop = c(100, 50)

【问题讨论】:

标签: r dplyr tidyverse


【解决方案1】:

dplyr 的一种可能是:

df %>%
 rename_at(2:length(.), list(~ substr(., 2, nchar(.))))

    country gdp pop
1        US 100 100
2 Australia  50  50

base R:

names(df)[-1] <- substr(names(df)[-1], 2, nchar(names(df)[-1]))

【讨论】:

    【解决方案2】:

    使用regex,我们可以提取除第一个字符以外的所有内容并指定名称。

    names(df)[-1] <- sub("^.(.*)$", "\\1", names(df)[-1])
    
    df
    #    country gdp pop
    #1        US 100 100
    #2 Australia  50  50
    

    【讨论】:

      【解决方案3】:

      这是一种方法

      library(stringr)
      
      names(df)[-1] = str_sub(names(df)[-1], 2)
      

      【讨论】:

      • 除此之外,如果您想使用基本函数,可以将str_sub 替换为substring
      【解决方案4】:

      也可以这样做:

      base(可以使用setdiff%in% 来“自动”选择。):

      sapply(names(df), function(x) ifelse(x=="country",x,substring(x,2,nchar(x))))
      

      tidyverse 不太优雅,因为 rename_at 已显示:

      names(df)<-unlist(names(df) %>% 
        map(.,function(x) ifelse(x=="country",x,substring(x,2,nchar(x)))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 2019-09-04
        • 2019-08-19
        • 2020-12-18
        • 2018-04-03
        • 1970-01-01
        相关资源
        最近更新 更多