w.fahey
w.fahey

Reputation: 17

R: Unstack a table to reduce the dimensional

I have a dataframe that looks like this:

x1 <- read.table(header=T, text="
Batch   Parameter   V1  V2  V3  V4  V5
Batch1  Parameter1  a   b   c   d   e
Batch1  Parameter2  f   h   i   j   k
Batch1  Parameter3  l   m   n   o   p
             ")

I would like to reformat (unstack?) in order to get this output:

a <- c("Batch", "Parameter1 V1",    "Parameter1 V2",    "Parameter1 V3",     
"Parameter1 V4",    "Parameter1 V5",    "Parameter2 V1",    "Parameter2 V2",     
"Parameter2 V3",    "Parameter2 V4",    "Parameter2 V5")
b <- c("Batch1","a", "b", "c", "d", "e", "f", "h", "i", "j", "k")

x2 <- rbind(a,b)

I have tried to use unstack():

x3 <- unstack(x1, x1$Batch+x1$Parameter~V1:V5)

But this does not produce the required output.

Any help would be greatly appreciated

W.

Upvotes: 1

Views: 60

Answers (1)

iod
iod

Reputation: 7592

require(tidyr)
require(dplyr)
x1 %>% 
 gather("V","value",V1:V5) %>% 
 mutate(Parameter=paste0(Parameter,".",V)) %>% 
 select(-V) %>% 
 spread(Parameter,value)

Since you want to end up with one row of all combinations of parameters and V's, you start by creating one longdata format of all of these - and from there it's easy to spread it to the wide format.

   Batch Parameter1.V1 Parameter1.V2 Parameter1.V3 Parameter1.V4 Parameter1.V5 Parameter2.V1
1 Batch1             a             b             c             d             e             f
  Parameter2.V2 Parameter2.V3 Parameter2.V4 Parameter2.V5 Parameter3.V1 Parameter3.V2 Parameter3.V3
1             h             i             j             k             l             m             n
  Parameter3.V4 Parameter3.V5
1             o             p

Upvotes: 1

Related Questions