tidyverse:数据转换,gather()

tidyverse: data transformation, gather()

我正在尝试转换数据集: [1]: https://i.stack.imgur.com/09Ioo.png

像这样: [2]: https://i.stack.imgur.com/vKKu2.png

我如何在 R 上执行此操作?我尝试使用 gather() 但不知何故我没有得到结果..

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

在此先感谢您的帮助!

因为您没有以易于重复使用的形式提供数据,这里有一个类似于您的虚拟数据框:

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))

要将数据转换为您显示的形式,您可以使用 pivot_longer(取代 gather),然后根据需要更改名称。

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

这是另一种tidyverse方法:

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