1

我有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))

非常感谢

4

2 回答 2

2

为此,请尝试使用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 创建

于 2021-03-18T23:01:07.430 回答
0

您可以使用sub

x <- 'X745.971008.Nanometers'
sub('X(\\d+\\.\\d+).Nanometers', '\\1_nm', x)
#[1] "745.971008_nm"

如果是列名,请尝试:

colnames(df) <- sub('X(\\d+\\.\\d+).Nanometers', '\\1_nm', colnames(df))

如果要对值进行四舍五入:

paste0(round(as.numeric(sub('X(\\d+\\.\\d+).Nanometers', '\\1',x)), 3), '_nm')
#[1] "745.971_nm"
于 2021-03-19T01:52:25.060 回答