在r中使用expand.grid()重新生成 Dataframe

jhkqcmku  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(101)

我想知道是否有可能复制我的Data下面也许使用tidyr::expand_grid()
变量mot可以取round(runif(8,1,4),1)产生的任何其他值,并且在每个time值上是常数(就像task一样)。
变量order显示tasktime上的顺序。例如,对于id=1,在time=1上,tasktime=2上,complexc上,order的值为s-c
我尝试了以下方法,但没有成功:

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
"
hlswsv35

hlswsv351#

rep()eachtimes的各种组合构成:

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

相关问题