0

I have a dataframe that looks like this:

 P   sample    sensor1    sensor2    sensor3........sensorP
 a   1         2.45       3.56       2.345          2.33
 a   2         2.37       3.46       2.22           1.98
 a   3         2.78       3.22       1.45           2.67
 a   N

I want it to look like this:

P  1_sensor1   2_sensor1   3_sensor1......N_sensorn1    2_sensor1    2_sensor2    
a  2.45        2.37        2.78                         3.56         3.46

and so on.... So split the sensors horiszontally and split the samples within each horizonatally too. I know its a reshape2 solution - I just can't get the syntax. The Sensors will have different names and the sample length can also vary...hence the N.

paul.

PaulBeales
  • 317
  • 3
  • 15
  • not really i want to split multiple cols with multiple samples this example doesn't do that – PaulBeales Nov 23 '17 at 11:47
  • It does exactly that; your column `P` is analogous to their column `ID`, your column `sample` is analogous to `TIME`, `sensor1` to `X`, and `sensor2` to `Y`; it translates exactly to what you're doing. Assuming your data frame is named `df`, just try this: `dcast(melt(df, id.vars=c("P", "sample")), P~variable+sample)` -- which is the solution to the linked duplicate question -- and you'll see what I mean. – duckmayr Nov 23 '17 at 12:00
  • OK - I stand corrected, it worked exactly how I needed it...! Thanks for taking the time to re-explain. – PaulBeales Nov 23 '17 at 12:41

1 Answers1

0

You can try with tidyverse package. Like this:

library(tidyverse)
data <- data.frame(sample = 1:4,
               sensor1 = rnorm(4, 2), 
               sensor2 = rnorm(4, 2), 
               sensor3 = rnorm(4, 2), 
               sensor4 = rnorm(4, 2))
data %>% 
  gather(sensor, value, sensor1:sensor4) %>%
  unite(names, sample, sensor) %>%
  spread(names, value)

The result is something like you are looking for:

  1_sensor1 1_sensor2 1_sensor3 1_sensor4 2_sensor1 2_sensor2 2_sensor3 2_sensor4
[1]  1.549545  3.166664 0.9557496  2.745318  2.246499  2.597675  3.352947  3.085531
  3_sensor1 3_sensor2 3_sensor3 3_sensor4 4_sensor1 4_sensor2 4_sensor3 4_sensor4
[1]  1.879149   3.82827   3.84254  3.052806  1.529147 0.6595416  1.286521  2.302484
gavg712
  • 170
  • 10