r - 根据命名向量 (R) 更改列名
问题描述
我有以下数据框:
a b c d e f g h i j
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
以及以下向量(或数据框)
sample name
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
我想根据第二个数据帧重命名第一个数据帧上的列:
1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
解决方案
我们可能会使用match
names(df1) <- df2$name[match(names(df1), df2$sample)]
-输出
> df1
1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1 1 1
3 1 1 1 1 1 1 1 1 1 1
4 1 1 1 1 1 1 1 1 1 1
或者使用命名向量来匹配
names(df1) <- setNames(df2$name, df2$sample)[names(df1)]
数据
df1 <- structure(list(a = c(1L, 1L, 1L, 1L), b = c(1L, 1L, 1L, 1L),
c = c(1L, 1L, 1L, 1L), d = c(1L, 1L, 1L, 1L), e = c(1L, 1L,
1L, 1L), f = c(1L, 1L, 1L, 1L), g = c(1L, 1L, 1L, 1L), h = c(1L,
1L, 1L, 1L), i = c(1L, 1L, 1L, 1L), j = c(1L, 1L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-4L))
df2 <- structure(list(sample = c("a", "b", "c", "d", "e", "f", "g",
"h", "i", "j"), name = 1:10), class = "data.frame", row.names = c(NA,
-10L))
推荐阅读
- python.net - Python.net - 远程控制 WPF 应用程序 - WPF 资源问题
- apache-kafka - 可以为每次发布添加未来回调吗?
- python - 我为合并排序编写了一个递归程序。如何通过绘制其运行时间与python中的输入图来分析它的时间复杂度
- ruby-on-rails - 如何从代码中运行 Minitest 中的单个测试?
- python-3.x - 无法使用 accessToken 而不是 idToken - msal python
- javascript - 拍摄 Windy(传单)截图
- python - 大熊猫中按日期分组的分类区域堆栈图
- javascript - Js-IPFS 错误:cid.toBaseEncodedString() 不是函数
- android - 在 android 中使用 TextRecognizer
- bash - zsh:如何将变量扩展为多个参数?