使用 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
Obs:您也可以将 colnames c("Age", "Height", "Weight") 直接传递到 cbind 中。