在R中,我想从以下数据框中为每个列名创建一个新的数据框:
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分别使用agedf,heightdf和weightdf列创建一个数据框。即最终得到3个数据框,如这张Excel照片所示: Excel desired result
我该怎么做?
答案 0 :(得分:0)
使用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")}
输出:
> 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]))}
这将提供与以前相同的输出,只是不在列表中。
最后,如果要将它们全部添加到单个数据框中,并指定每个观察值来自何处:
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)
输出:
> 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
糟糕:您也可以通过其他方法将c("Age", "Height", "Weight")
的姓氏直接传递到cbind
。
答案 1 :(得分:0)
这是使用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