'tidyverse: data transformation, gather()

I am trying to transform a dataset: [1]: https://i.stack.imgur.com/09Ioo.png

To something like this: [2]: https://i.stack.imgur.com/vKKu2.png

How can I do this on R? I tried using gather() but somehow im not getting the results..

library(tidyverse)
df_gather <- df %>% gather(key = "Day", "Sensor",2:5)
View(df_gather)

Thanks in advance for your help!



Solution 1:[1]

Here is another tidyverse approach:

dat %>% 
  rename_with(., ~str_replace_all(., "Sensor", "Time_")) %>% 
  pivot_longer(-Date,
               names_sep = "_",
               names_to = c(".value", "Sensor")  
               )
    Date Sensor  Time
   <int> <chr>  <dbl>
 1     1 1       155.
 2     1 2       160.
 3     1 3       126.
 4     1 4       162.
 5     1 5       155.
 6     2 1       126.
 7     2 2       133.
 8     2 3       155.
 9     2 4       171.
10     2 5       154.
# … with 15 more rows

Solution 2:[2]

Because you did not provide the data in an easily reused form, here is a dummy data frame similar to yours:

dat <-structure(list(Date = 1:5, Sensor1 = c(154.501112480648, 125.564142037183, 
184.578892146237, 155.085407197475, 176.232917583548), Sensor2 = c(159.958130051382, 
132.943481742404, 100.740377581678, 178.590174368583, 182.851045904681
), Sensor3 = c(125.962588260882, 155.333150480874, 122.294128965586, 
122.685094899498, 150.199430575594), Sensor4 = c(162.315403693356, 
170.65782523714, 117.775949183851, 145.122508681379, 193.589874636382
), Sensor5 = c(154.887120774947, 154.432400292717, 139.244429254904, 
180.038237478584, 160.314362798817)), class = "data.frame", row.names = c(NA, 
-5L))

To transform the data to the form you showed, you can use pivot_longer (which superseded gather) and then changed the names as necessary.

dat |> 
  pivot_longer(cols = starts_with("Sensor")) |> 
  mutate(name = str_replace(name, "Sensor", "")) |> 
  rename(Day = Date, Sensor = name, Time = value)

# The result

# A tibble: 25 × 3
     Day Sensor  Time
   <int> <chr>  <dbl>
 1     1 1       155.
 2     1 2       160.
 3     1 3       126.
 4     1 4       162.
 5     1 5       155.
 6     2 1       126.
 7     2 2       133.
 8     2 3       155.
 9     2 4       171.
10     2 5       154.
# … with 15 more rows

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TarJae
Solution 2 Abdur Rohman