我将如何创建该数据框?我需要使用嵌套的for循环吗?

时间:2019-05-02 01:33:47

标签: r for-loop nested

我正在尝试创建一个具有两列(ID,条件)的数据框。每个ID与8个条件链接。 ID从s009开始,范围为s050。对于每个ID,我将具有相同的一组条件。我提供了一个示例集,供我参考。我将不胜感激与此有关的任何帮助。预先感谢!

ID     Condition
s009    Baseline
s009    Meditation
s009    Practice
s009    Creativity
s009    Preblock 1
s009    Postblock 1
s009    Preblock 2
s009    Postblock 2
s010    Baseline
s010    Mediation
s010    Practice 
s010    Creativity
s010    Preblock 1
s010    Postblock 1
s010    Preblock 2
s010    Postblock 2
s011    Baseline
...

3 个答案:

答案 0 :(得分:2)

一个选项是expand.grid中的base R(不使用任何外部软件包)

df1 <- expand.grid(ID = v1, Condition = v2)

或使用data.table

library(data.table)
CJ(ID = v1, Condition = v2)
#    ID   Condition
#  1: s009    Baseline
#  2: s009  Creativity
#  3: s009  Meditation
#  4: s009 Postblock 1
#  5: s009 Postblock 2
# ---                 
#332: s050 Postblock 1
#333: s050 Postblock 2
#334: s050    Practice
#335: s050  Preblock 1
#336: s050  Preblock 2

或使用tidyverse

library(tidyverse)
tibble(ID = v1) %>% 
    expand(ID, Condition = v2)
# A tibble: 336 x 2
#   ID    Condition  
#   <chr> <chr>      
# 1 s009  Baseline   
# 2 s009  Creativity 
# 3 s009  Meditation 
# 4 s009  Postblock 1
# 5 s009  Postblock 2
# 6 s009  Practice   
# 7 s009  Preblock 1 
# 8 s009  Preblock 2 
# 9 s010  Baseline   
#10 s010  Creativity 
# … with 326 more rows

其中

v1 <- sprintf("s%03d", 9:50)
v2 <- c("Baseline", "Meditation", "Practice", "Creativity",
    "Preblock 1", "Postblock 1", "Preblock 2", "Postblock 2")

答案 1 :(得分:1)

我们可以创建两个向量IDCodition并使用crossing

Condition <- c("Baseline","Meditation", "Practice", "Creativity" , "Preblock 1", 
             "Postblock 1", "Preblock 2", "Postblock 2")
ID <- paste0("s", sprintf("%03d", 9:50))

tidyr::crossing(ID, Condition)

#   ID    Condition  
#   <chr> <chr>      
# 1 s009  Baseline   
# 2 s009  Creativity 
# 3 s009  Meditation 
# 4 s009  Postblock 1
# 5 s009  Postblock 2
# 6 s009  Practice   
# 7 s009  Preblock 1 
# 8 s009  Preblock 2 
# 9 s010  Baseline   
#10 s010  Creativity 
# … with 326 more rows

我们也可以在基数R中使用merge

merge(ID, Condition)

答案 2 :(得分:0)

这是另一种解决方案:

library(stringr)

ID <- sort(rep(paste0('s', str_pad(9:50, width=3, side='left', pad='0')),8))
Condition <- rep(c('Baseline', 'Meditation', 'Practice', 'Creativity', 'Preblock 1', 'Postblock 1', 'Preblock 2', 'Postblock 2'), 8*42)

df <- data.frame(ID, Condition)