r - R中的列名 - 替换名称字符串的一部分
问题描述
我有X745.971008.Nanometers
as 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))
非常感谢
解决方案
为此,请尝试使用rename_all
and 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 创建
推荐阅读
- r - R编程felm管道与因子()
- c - C remove() 函数在 windows 环境下不删除目标文件
- assembly - ASM - IN 0x64 和 IN 0x60 用于鼠标输入
- android - Android Things - Raspberry Pi 3 B - adb install apk - 安装失败的旧 SDK
- oracle - 如何在Oracle中将数字转换为日期?
- laravel - 如何制定在某些情况下覆盖另一个的自定义 Laravel 策略?
- c++ - 如何将时间(chrono)除以给定值
- oracle-sqldeveloper - 如何在 Oracle-sqldeveloper 中仅获取一年中月份的一位数字或字符
- html - 创建对角线蒙版效果
- python - Python函数返回错误值