donovanw
donovanw

Reputation: 17

R Table Formatting

I have a dataset that is available in the following format:

Metric 1    Metric 2    Metric 1    Metric 2    Metric 1    Metric 2
4           4           4           4           4           78
4           4           4           4           4           -4
45          45          45          45          45          37
5           5           5           5           5           -3

But I wish to almost transpose the data into two columns like so:

Metric 1    Metric 2
4           4
4           4
45          45
5           5
4           4
4           4
45          45
5           5
4           78
4           -4
45          37
5           -3

I've looked around and haven't quite found a solution that I've been able to implement. Does anyone have any advice? I understand this is likely a simple solution.

Upvotes: 0

Views: 52

Answers (2)

BENY
BENY

Reputation: 323386

Or you can try this using melt

df=melt(df)
data.frame('Metric 1'=df$value[df$variable=='Metric 1'],
           'Metric 2'=df$value[df$variable=='Metric 2'])

   Metric.1 Metric.2
1         4        4
2         4        4
3        45       45
4         5        5
5         4        4
6         4        4
7        45       45
8         5        5
9         4        4
10        4        4
11       45       45
12        5        5

Upvotes: 0

d.b
d.b

Reputation: 32558

FYI, it is better to have unique column names.

If your data looks like in the question, you could split chunks of 2 columns at one time and then rbind them

do.call(rbind, lapply(seq(1, NCOL(df), 2), function(i) df[,i:(i+1)]))
#   Metric 1 Metric 2
#1         4        4
#2         4        4
#3        45       45
#4         5        5
#5         4        4
#6         4        4
#7        45       45
#8         5        5
#9         4       78
#10        4       -4
#11       45       37
#12        5       -3

DATA

df = structure(list(`Metric 1` = c(4L, 4L, 45L, 5L), `Metric 2` = c(4L, 
4L, 45L, 5L), `Metric 1` = c(4L, 4L, 45L, 5L), `Metric 2` = c(4L, 
4L, 45L, 5L), `Metric 1` = c(4L, 4L, 45L, 5L), `Metric 2` = c(78L, 
-4L, 37L, -3L)), .Names = c("Metric 1", "Metric 2", "Metric 1", 
"Metric 2", "Metric 1", "Metric 2"), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 2

Related Questions