Home > Back-end >  Reproduce a dataframe using expand.grid() in r
Reproduce a dataframe using expand.grid() in r

Time:12-15

I wonder if it might be possible to reproduce my Data below perhaps using tidyr::expand_grid()?

The variable mot can take any other values produced by round(runif(8,1,4),1) and is constant at each time value (just like task).

Variable order shows the task order across time. For example, for id=1 at time=1 task is simple (s) at time=2 complex (c), thus order value is s-c.

I tried the following without success:

library(tidyr)
expand_grid(class=1:2, id=1:4, oder=c("s-c","c-s"),time=1:2, 
            task=c("simple","complex"))
Data ="
class id   order time DV  task      mot
1     1    s-c   1    ac  simple    1.5
1     1    s-c   1    bc  simple    1.5
1     1    s-c   2    ac  complex   2.3
1     1    s-c   2    bc  complex   2.3

1     2    c-s   1    ac  complex   3.9
1     2    c-s   1    bc  complex   3.9
1     2    c-s   2    ac  simple    4.0
1     2    c-s   2    bc  simple    4.0

2     3    s-c   1    ac  simple    2.7
2     3    s-c   1    bc  simple    2.7
2     3    s-c   2    ac  complex   1.2
2     3    s-c   2    bc  complex   1.2

2     4    c-s   1    ac  complex   2.8
2     4    c-s   1    bc  complex   2.8
2     4    c-s   2    ac  simple    1.1
2     4    c-s   2    bc  simple    1.1
"

CodePudding user response:

rep() with various combinations of each, and times makes:

library(tidyverse)
df <- tibble(class=rep(1:2, each=8), 
       id=rep(1:4, each=4),
       order=rep(c("s-c", "c-s"), each=4, times=2),
       time=rep(1:2, each=2, times=4),
       DV=rep(c("ac", "bc"), each=1, times=8),
       task=rep(c("simple", "complex", "complex", "simple"), each=2, times=2),

       mot=rep(round(runif(8,1,4),1), each=2))
# A tibble: 16 × 7
   class    id order  time DV    task      mot
   <int> <int> <chr> <int> <chr> <chr>   <dbl>
 1     1     1 s-c       1 ac    simple    3  
 2     1     1 s-c       1 bc    simple    3  
 3     1     1 s-c       2 ac    complex   1.4
 4     1     1 s-c       2 bc    complex   1.4
 5     1     2 c-s       1 ac    complex   1.6
 6     1     2 c-s       1 bc    complex   1.6
 7     1     2 c-s       2 ac    simple    1.6
 8     1     2 c-s       2 bc    simple    1.6
 9     2     3 s-c       1 ac    simple    2.1
10     2     3 s-c       1 bc    simple    2.1
11     2     3 s-c       2 ac    complex   2.3
12     2     3 s-c       2 bc    complex   2.3
13     2     4 c-s       1 ac    complex   3.7
14     2     4 c-s       1 bc    complex   3.7
15     2     4 c-s       2 ac    simple    2.4
16     2     4 c-s       2 bc    simple    2.4
  • Related