Reputation: 433
I have two columns of data (as given in the code below), and I don't know how to stack them into one column in a customized order. To be clear, I want a single column (call it x) as my dataset, with entries 1-5 of column "attr" as entries 1-5 of column x, followed by entries 6-10 of column "type" as entries 6-10 in column x, followed entries 6-10 of column "attr" as entries 11-15 in column x, followed finally by entries 6-10 of column "type" as entries 16-20 in column x. My dataset is below:
analysis <- data.frame(attr = c('player_a', 'player_b', 'player_c', 'player_d', 'player_e',
'player_f', 'player_g', 'player_h', 'player_i', 'player_j'),
type = c('player_q', 'player_r', 'player_s', 'player_t', 'player_u',
'player_v', 'player_w', 'player_x', 'player_y', 'player_z'))
I am fairly new to R, so I apologize if I used incorrect terminology. Any help is greatly appreciated
To clarify, my desired order is:
player_a
player_b
player_c
player_d
player_e
player_q
player_r
player_s
player_t
player_u
player_f
player_g
player_h
player_i
player_j
player_v
player_w
player_x
player_y
player_z
Upvotes: 1
Views: 49
Reputation: 1220
Here is my answer which uses the dplyr
package but I'm sure you could use the same logic with data.table
or base
library(dplyr)
library(tidyr)
analysis <- data.frame(attr = c('player_a', 'player_b', 'player_c',
'player_d', 'player_e', 'player1', 'player2',
'player3', 'player4', 'player5'),
type=c('player_v','player_w','player_x',
'player_y', 'player_z','player6', 'player7',
'player8', 'player9', 'player10'))
a2 <- mutate(analysis, order = c(rep(1,5),rep(2,5)))
a3 <- gather(a2, "variable", "value", -order) %>% arrange(order)
Upvotes: 0
Reputation: 469
Is this what you are looking for (uses data.table package)?
library(data.table)
analysis <- data.table(attr = c('player_a', 'player_b', 'player_c', 'player_d', 'player_e'), type=c('player_v','player_w','player_x', 'player_y', 'player_z'))
melt(analysis,measure.vars = 1:2)
variable value
1: attr player_a
2: attr player_b
3: attr player_c
4: attr player_d
5: attr player_e
6: type player_v
7: type player_w
8: type player_x
9: type player_y
10: type player_z
Upvotes: 1