初始数据框如下所示
A B Ca Da Ea Fb Gb Hb
12 11 1 2 4 3 3 3
16 14 3 0 5 1 0 1
14 12 2 4 5 2 1 1
17 17 2 4 5 2 0 1
通过保持值(使值相关联),值A和B应该相同。 Ca,Da,Ea对应于A和Fb,Gb,Hb对应于B.
这是所需的输出:
A B Ca Da Ea Fb Gb Hb
12 12 1 2 4 2 1 1
14 14 2 4 5 1 0 1
17 17 2 4 5 2 0 1
数据
# Reproducible dummy data
dat = read.table(text = "A B Ca Da Ea Fb Gb Hb
12 11 1 2 4 3 3 3
16 14 3 0 5 1 0 1
14 12 2 4 5 2 1 1
17 17 2 4 5 2 0 1", header = TRUE)
答案 0 :(得分:1)
您可以使用merge
Reduce
相应地划分出来
# list of possible column names
colnames = c(paste('[',toupper(letters[1:2]),letters[1:2],']', sep= ''))
# list of dataframes
dflist = lapply(colnames, function(y) dat[,grep(y, colnames(dat))])
# dataframe list merge
out = Reduce(function(...) merge(..., by = 1), dflist)
#> out
# A Ca Da Ea Fb Gb Hb
#1 12 1 2 4 2 1 1
#2 14 2 4 5 1 0 1
#3 17 2 4 5 2 0 1