rewriting a table/data frame in r

241 views Asked by At

Here is an example of my data set:

Sensor ---- Time(GMT) ----- Temperature (°C)

1 ------- 24/06/2002 05:02:01 --- 33.855

2 ------- 24/06/2002 05:02:01 --- 33.827

3 ------- 24/06/2002 05:02:01 --- 33.104

4 ------- 24/06/2002 05:02:01 --- 33.787

1 ------- 24/06/2002 05:02:02 --- 33.609

2 ------- 24/06/2002 05:02:02 --- 33.609

3 ------- 24/06/2002 05:02:02 --- 33.610

4 ------- 24/06/2002 05:02:02 --- 33.608

To be able to work with it I have to rewrite this dataset, so that it looks like this:

Time ---------------------- Sensor1 - Sensor2 - Sensor3 -Sensor4

24/06/2002 05:02:01 -- 33.855 -- 33.827 -- 33.104 -- 33.787

24/06/2002 05:02:02 --33.609 -- 33.609 -- 33.610 -- 33.608

I'm a beginner in R, so this is pretty rough for me and I would be verv happy about suggestions or proposed solutions. Thanks.

1

There are 1 answers

1
dario On

1.Creating an example data set:

df <- structure(list(Sensor = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L),
                     Time = c("24/06/2002 05:02:01", "24/06/2002 05:02:01", "24/06/2002 05:02:01", "24/06/2002 05:02:01",
                              "24/06/2002 05:02:02", "24/06/2002 05:02:02", "24/06/2002 05:02:02","24/06/2002 05:02:02"),
                     Temp = c(33.855, 33.827, 33.104, 33.787, 33.609, 33.609, 33.61, 33.608)),
                row.names = c(NA, -8L),
                class = c("data.table", "data.frame"))

2.Suggested solution using tidyr pivot_wider, a function that does exactly what you want ;)

library(dplyr)
library(tidyr)

df %>% 
  pivot_wider(names_from = Sensor, values_from = Temp, names_prefix="Sensor")

This Returns:

# A tibble: 2 x 5
  Time                Sensor1 Sensor2 Sensor3 Sensor4
  <chr>                 <dbl>   <dbl>   <dbl>   <dbl>
1 24/06/2002 05:02:01    33.9    33.8    33.1    33.8
2 24/06/2002 05:02:02    33.6    33.6    33.6    33.6

P.S. Actually there is no reason to use dplyr syntax, so here is the solution using only tidyr::pivot_wider:

pivot_wider(df, names_from = Sensor, values_from = Temp, names_prefix="Sensor")

Edit

Removed accidental dependency on data.table