我有一個包含多個 Participant_ID 的資料框。對于每個 Participant_ID,我有 4 個變數(Start_day、End_day、Lights_out 和 Got_up),每個變數有 48 天(此處命名為:...2 - ...3 - ...):

我想要 6 列:id-days - Start_day - End_day - Lights_out - Got_up
基本上,保留“id”列并使用天數切換變數(...2,...3,...4,...)
有誰知道這是怎么做到的嗎?非常感謝!
uj5u.com熱心網友回復:
如果我理解正確,可以tidyverse使用包中的pivot函式解決問題tidyr:
library(dplyr)
library(tidyr)
# dummy data
df <- data.frame(id = c("ALM-M", "ALM-M", "ALM-M", "ALM-M"),
variable = c("Start day", "End day", "Lights out", "Got Up"),
col1 = c(44269, 44269, 4.1319, 0.3128),
col2 = c(44270, 44270, 0.1928, 0.4223))
# convert data (first make it longer, than wider)
tidyr::pivot_longer(df, -c(id, variable), names_to = "cols", values_to = "vals") %>%
tidyr::pivot_wider(names_from = variable, values_from = vals)
# A tibble: 2 x 6
id cols `Start day` `End day` `Lights out` `Got Up`
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 ALM-M col1 44269 44269 4.13 0.313
2 ALM-M col2 44270 44270 0.193 0.422
在這里你可以找到一些關于使用包中pivot函式的更深入的解釋tidyr。
uj5u.com熱心網友回復:
我們可以使用tidyr::pivot_longer和tidyr::pivot_wider
示例資料
dat<- tibble(id = 'participant_1',
variables = c('Start_day','End_day','Lights_out', 'Got_up'),
`...1`=c(0,1,2,3),
`...2`=c(5,6,7,8),
`...3`=c(0,1,2,3),
`...4`=c(0,1,2,3))
# A tibble: 4 × 6
id variables ...1 ...2 ...3 ...4
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 participant_1 Start_day 0 5 0 0
2 participant_1 End_day 1 6 1 1
3 participant_1 Lights_out 2 7 2 2
4 participant_1 Got_up 3 8 3 3
回答
dat %>%
pivot_longer(`...1`:`...4`) %>%
pivot_wider(names_from = variables, values_from = value)
# A tibble: 4 × 6
id name Start_day End_day Lights_out Got_up
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 participant_1 ...1 0 1 2 3
2 participant_1 ...2 5 6 7 8
3 participant_1 ...3 0 1 2 3
4 participant_1 ...4 0 1 2 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394819.html
