gpt4 book ai didi

r - 根据命名向量 (R) 更改列名

转载 作者:行者123 更新时间:2023-12-05 02:40:02 25 4
gpt4 key购买 nike

我有以下数据框:

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

关于r - 根据命名向量 (R) 更改列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68821914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com