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