![](/img/trans.png)
[英]Merging dataframes with identical column names getting separated columns, in R
[英]How to create a new dataframe by merging columns with identical names from different dataframes in R?
在 R 中,我想从以下数据框中为每个列名称创建一个新的 dataframe:
agedf <- data.frame(A = c(12,14,16,18), B = c(13,15,17,19), C = c(11,13,15,17))
heightdf <- data.frame(A = c(110,120,130,140), B = c(120,130,140,150), C = c(115,125,135,145))
weightdf <- data.frame(A = c(80,90,100,110), B = c(90,100,110,120), C = c(85,95,105,115))
期望的结果是有一个公式,为 A、B 和 C 中的每一个创建一个 dataframe 及其各自的 agedf、heightdf 和 weightdf 列。 即最终得到 3 个数据帧,如这张 Excel 照片所示: Excel 期望的结果
我怎样才能做到最好?
使用 for 循环(可能有类似tidyr
或dplyr
的包装替代品):
newlist = list()
names = colnames(agedf)
for(i in names){
index = which(colnames(agedf)==i)
newlist[[i]] = cbind(agedf[,index], heightdf[,index], weightdf[,index])
colnames(newlist[[i]]) = c("Age", "Height", "Weight")}
Output:
> newlist
$A
Age Height Weight
[1,] 12 110 80
[2,] 14 120 90
[3,] 16 130 100
[4,] 18 140 110
$B
Age Height Weight
[1,] 13 120 90
[2,] 15 130 100
[3,] 17 140 110
[4,] 19 150 120
$C
Age Height Weight
[1,] 11 115 85
[2,] 13 125 95
[3,] 15 135 105
[4,] 17 145 115
不使用列表,并为每个names
创建一个新的 df :
names = colnames(agedf)
for(i in names){
index = which(colnames(agedf)==i)
assign(i, cbind("Age"=agedf[,index], "Height"=heightdf[,index], "Weight"=weightdf[,index]))}
这给出了与之前相同的 output,只是不在列表中。
最后,如果您想将它们全部添加到一个数据框中,并指定每个观察结果的来源:
df = numeric()
names = colnames(agedf)
for(i in names){
index = which(colnames(agedf)==i)
df = rbind(df, cbind(i, agedf[,index], heightdf[,index], weightdf[,index]))}
colnames(df) = c("Code", "Age", "Height", "Weight")
df = as.data.frame(df)
Output:
> df
Code Age Height Weight
1 A 12 110 80
2 A 14 120 90
3 A 16 130 100
4 A 18 140 110
5 B 13 120 90
6 B 15 130 100
7 B 17 140 110
8 B 19 150 120
9 C 11 115 85
10 C 13 125 95
11 C 15 135 105
12 C 17 145 115
Obs:您也可以在另一种方法中将 colnames c("Age", "Height", "Weight")
直接传递到cbind
中。
这是使用tidyverse
的一种方法。
library(dplyr)
library(purrr)
df_list <- list(Age = agedf,
Height = heightdf,
Weight = weightdf)
map(transpose(df_list), bind_cols)
# $A
# # A tibble: 4 x 3
# Age Height Weight
# <dbl> <dbl> <dbl>
# 1 12 110 80
# 2 14 120 90
# 3 16 130 100
# 4 18 140 110
#
# $B
# # A tibble: 4 x 3
# Age Height Weight
# <dbl> <dbl> <dbl>
# 1 13 120 90
# 2 15 130 100
# 3 17 140 110
# 4 19 150 120
#
# $C
# # A tibble: 4 x 3
# Age Height Weight
# <dbl> <dbl> <dbl>
# 1 11 115 85
# 2 13 125 95
# 3 15 135 105
# 4 17 145 115
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.