【问题标题】:Deleting the first 4 characters of my col names in R [duplicate]在R中删除我的col名称的前4个字符[重复]
【发布时间】:2022-01-23 22:47:59
【问题描述】:

我正在尝试使用 stringr 删除列名的前 4 个字符。我知道如何指定我要保留的字符,但是由于每列长度不同,我需要指定我不想保留的字符,我不知道该怎么做。

我该怎么做?

【问题讨论】:

    标签: r string stringr


    【解决方案1】:

    这不是最好的方法,但应该在这里提供Base R 的替代方法。

    substr(state.name,5,nchar(state.name))
    # [1] "ama"        "ka"         "ona"        "nsas"       "fornia"     "rado"       "ecticut" 
    

    【讨论】:

      【解决方案2】:

      您可能会发现这对重命名列很有用。

      library(dplyr)
      library(stringr)
      
      df %>% 
        rename_with(str_sub, start = 5L)
      

      如果您不想对所有列都这样做,可以使用.cols 参数。

      # like this
      iris %>% 
        rename_with(str_sub, start = 5L, .cols = starts_with("Sepal"))
      
      # or this
      iris %>% 
        rename_with(str_sub, start = 5L, .cols = 1:2)
      
      # or this, and so on...
      iris %>% 
        rename_with(str_sub, start = 5L, .cols = c("Petal.Length", "Species"))
      

      【讨论】:

        【解决方案3】:

        stringr 很好,但这里有一个非常好的解决方案存在于基础 R 中。

        x <- head(state.name)
        x 
        # [1] "Alabama"    "Alaska"     "Arizona"    "Arkansas"   "California" "Colorado"
        substring(x, 5)
        # [1] "ama"    "ka"     "ona"    "nsas"   "fornia" "rado"
        

        【讨论】:

        • 这给了我一个类似列表的东西,它不能代替列的名称
        • 输入应该是一个向量。因此,如果您想修改 data.frame 的(列)名称,您可以 names(df) &lt;- substring(names(df), 5)
        • 现在我已经找到了解决方案。谢谢
        • 我同意这个应该不需要去stringr包,但是如果它是严格要求的(出于某种原因),那么用stringr::str_sub替换substring就可以了一切都一样。 (尽管substring 使用此示例数据 3 倍以上。直到length(x) 处于1000 年代中期,它才接近速度平价。)
        猜你喜欢
        • 1970-01-01
        • 2018-05-17
        • 2019-03-27
        • 2020-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多