首页 > 解决方案 > R中的列名 - 替换名称字符串的一部分

问题描述

我有X745.971008.Nanometersas col 名称,但不知道如何使用以下格式:

我想要col名称:745.971008_nm

或更好,波长四舍五入为 3 dp:745.971_nm

我努力了:names(df) <- sub('X\\.+(\\d+\\.\\d+)\\.Nanometers\\.', '\\1_nm', names(df))

和:colnames(df) <- gsub("X(.+).Nanometers.", "\\1_nm", colnames(df))

非常感谢

标签: r

解决方案


为此,请尝试使用rename_alland str_replace_all

我想这将是最准确的方法,因为它会按照您的要求对变量名称中的值进行四舍五入:

df <- data.frame(
  'X745.971008.Nanometers' = c(1, 2, 3, 4, 5),
  'X743.971999.Nanometers' = c(1, 2, 3, 4, 5)
)

library(dplyr)
library(stringr)

df %>% 
  stack() %>% 
  mutate(ind = str_replace(ind, 'X', ''),
         ind = str_replace(ind, '.Nanometers', ''),
         ind = paste(round(as.numeric(ind), digits = 3), '_nm')) %>%  
  unstack(df2, form = values~ind) %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., 'X', '')
    )
  ) %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., '._', '_')
    )
  )

#>   743.972_nm 745.971_nm
#> 1          1          1
#> 2          2          2
#> 3          3          3
#> 4          4          4
#> 5          5          5

reprex 包(v0.3.0)于 2021-03-18 创建

或者

df <- data.frame(
  'X745.971008.Nanometers' = c(1, 2, 3, 4, 5),
  'X743.971999.Nanometers' = c(1, 2, 3, 4, 5)
)

library(dplyr)
library(stringr)

df %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., 'X', '')
    )
  ) %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., '.Nanometers', '_nm')
    )
  )

#>   745.971008_nm 743.971999_nm
#> 1             1             1
#> 2             2             2
#> 3             3             3
#> 4             4             4
#> 5             5             5

reprex 包(v0.3.0)于 2021-03-18 创建

或者

df <- data.frame(
  'X745.971008.Nanometers' = c(1, 2, 3, 4, 5),
  'X743.971999.Nanometers' = c(1, 2, 3, 4, 5)
)

library(dplyr)
library(stringr)

df %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., 'X', '')
    )
  ) %>% 
  rename_all(
    funs(
      stringr::str_replace_all(., '\\d\\d\\d.Nanometers', '_nm')
    )
  )

#>   745.971_nm 743.971_nm
#> 1          1          1
#> 2          2          2
#> 3          3          3
#> 4          4          4
#> 5          5          5

reprex 包(v0.3.0)于 2021-03-18 创建


推荐阅读