[英]Rename dataframe columns based on values in another dataframe in R
I have one data frame which has one column & two records in it. 我有一个数据框,其中有一列和两个记录。
DF1= DF1 =
Name
M_D
ABC123
I have another dataframe which has two columns. 我有另一个具有两列的数据框。 I need to rename second dataframe columns with two values in first data frame.
我需要在第一个数据帧中用两个值重命名第二个数据帧列。
DF2= DF2 =
PQR LMN
111 345
456 999
I want DF2 as below 我想要DF2如下
M_D ABC123
111 345
456 999
Thanks 谢谢
You can access values for column names for DF2
using $
or [[
operator on DF1
. 您可以为列名访问值
DF2
使用$
或[[
操作上DF1
。 Since OP has mentioned that he doesn't even know the column names of DF1
, an option could be as: 由于OP提到他甚至都不知道
DF1
的列名,因此可以使用以下选项:
names(DF2) <- DF1[,1]
DF2
# M_D ABC123
#1 111 345
#2 456 999
#OR
names(DF2) <- DF1[[1]]
#OR
names(DF2) <- DF1$Name
Note: names(DF2) <- DF1[1]
will not work as DF1[1]
is still of type data.frame
and names<-
expects a vector
. 注意:
names(DF2) <- DF1[1]
将不起作用,因为DF1[1]
仍然是data.frame
类型,并且names<-
需要一个vector
。
Data: 数据:
DF2 <- read.table(text =
"PQR LMN
111 345
456 999",
header = TRUE, stringsAsFactors = FALSE)
DF1 <- read.table(text =
"Name
M_D
ABC123",
header = TRUE, stringsAsFactors = FALSE)
Based on your comment above, I recommend hardcoding it with something like dplyr::rename()
. 根据上面的评论,我建议使用
dplyr::rename()
类的东西对其进行硬编码。
DF2 <- DF2 %>%
dplyr::rename(
M_D = PQR,
ABC123 = LMN
)
In my experience, you shouldn't really trust that collaborators will give you the same dataset structure each time. 以我的经验,您不应该真正相信协作者每次都会为您提供相同的数据集结构。 This will throw an error if they've changed the column names (this is good --you want to be alerted to the problem early in the pipeline).
如果他们更改了列名,这将引发错误(这很好-您希望在管道中尽早收到有关该问题的警报)。 If they've change the column order,
dplyr::rename()
will handle it gracefully & correctly. 如果他们更改了列顺序,则
dplyr::rename()
将优雅而正确地处理它。
Consider additional defensive programming tools like checkmate or testit to verify the column characteristics match your expectations ( eg , the PQR
/ M_D
column is an integer with values between 0 and 5). 考虑使用其他防御性编程工具(如checkmate或testit)来验证列特性是否符合您的期望( 例如 ,
PQR
/ M_D
列是一个介于0到5之间的整数)。
如果DF1 $ Name的长度与DF2的列数相同,这将起作用
colnames(DF2) <- DF1$Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.