user4760532
user4760532

Reputation:

Rearranging the dataframe based on matching values between two columns

The initial data frame looks like this

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

The values A and B should be the same by keeping the values (bring the values associated). Ca, Da, Ea corresponds to A and Fb, Gb,Hb corresponds to B.

Here is the desired output:

 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

data

# 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)

Upvotes: 1

Views: 55

Answers (1)

Veerendra Gadekar
Veerendra Gadekar

Reputation: 4472

You can divide the data into a list of dataframes and latter merge them accordingly using 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

Upvotes: 1

Related Questions