我正在尝试转换一个数据集: 1:https://i.stack.imgur.com/09Ioo.png
这样的: 2:https://i.stack.imgur.com/vKKu2.png
我怎样才能在R上做到这一点?我试着用道集(),但不知怎么的,我没有得到结果。
library(tidyverse)
df_gather <- df %>% gather(key = "Day", "Sensor",2:5)
View(df_gather)提前感谢您的帮助!
发布于 2022-05-13 07:54:49
下面是另一种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发布于 2022-05-13 04:17:50
由于您没有以易于重用的形式提供数据,下面是一个与您类似的虚拟数据框架:
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 rowshttps://stackoverflow.com/questions/72224311
复制相似问题