简体   繁体   English

R:使用 tidyr 创建纵向数据集

[英]R: creating a longitudinal dataset using tidyr

I am looking to generate a longitudinal dataset.我正在寻找生成纵向数据集。 I have generated my pat numbers and treatment groups:我已经生成了我的拍号和治疗组:

library(dplyr)
set.seed(420)
Pat_TNO <- 1001:1618

data.frame(Pat_TNO = Pat_TNO) %>%
  rowwise() %>%
  mutate(
    trt = rbinom(1, 1, 0.5)
  )

My timepoints (in days) are:我的时间点(以天为单位)是:

timepoint_weeks <- c(seq(2, 12, 2), 16, 20, 24, 52)
timepoint_days <- 7 * timepoint_weeks

How can I pivot this dataset using the vector timepoint_days , so I have 10 rows per participant and column names Pat_TNO , trt , timepoint_days .我如何使用向量timepoint_days pivot 这个数据集,所以我有每个参与者 10 行和列名Pat_TNOtrttimepoint_days

You can use the unnest function from tidyr to achieve what you want.您可以使用 tidyr 中的unnest tidyr来实现您想要的。

Here is the code这是代码

library(dplyr)
library(tidyr)
set.seed(420)
Pat_TNO <- 1001:1618

x <- data.frame(Pat_TNO = Pat_TNO) %>%
  rowwise() %>%
  mutate(
    trt = rbinom(1, 1, 0.5)
  )

timepoint_weeks <- c(seq(2, 12, 2), 16, 20, 24, 52)
timepoint_days <- 7 * timepoint_weeks

x %>% 
  mutate(timepoint_days = list(timepoint_days)) %>% 
  unnest()

Output Output

# A tibble: 6,180 × 3
   Pat_TNO   trt timepoint_days
     <int> <int>          <dbl>
 1    1001     1             14
 2    1001     1             28
 3    1001     1             42
 4    1001     1             56
 5    1001     1             70
 6    1001     1             84
 7    1001     1            112
 8    1001     1            140
 9    1001     1            168
10    1001     1            364
# … with 6,170 more rows

Here I used the mutate function to add a column with a list containing timepoint_days in every row.在这里,我使用mutate function 添加了一个列,其中包含每行中包含timepoint_days的列表。 And then unnest collapses each row to get 10 rows per participant.然后unnest折叠每一行以获得每个参与者 10 行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM