在R中组合两个表/数组

4nkexdtk  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(97)

使用我的Data,我想知道是否有一种方法可以实现我的Desired_outputtablematrix类的对象)?
我尝试了以下方法,但没有成功:

with(Data, table(group, task_type, time.))
Data = data.frame(group=rep(c("Sim","Com"), each=4), 
           task_type = c(rep(c("S","C"),2),rep(c("C","S"),2)),
           time = time <- rep(1:4,2), 
           time. = ifelse(time%%2==1, "odd", "even"))


Desired_output="
               task_type
  group      C         S
   Com      odd       even
   Sim      even      odd
  "
rqenqsqc

rqenqsqc1#

我们可以在用pivot_wider整形为"宽"并转换为table之前获得distinct

library(dplyr)
library(tidyr)
out <- Data %>% 
   distinct(group, task_type, time.) %>%
   pivot_wider(names_from = task_type, values_from = time.) %>% 
   column_to_rownames("group") %>%
   as.matrix %>%
   as.table
names(dimnames(out)) <- names(Data)[1:2]
  • 输出
> out
     task_type
group S    C   
  Sim odd  even
  Com even odd
gpnt7bae

gpnt7bae2#

或许:

bb <- with(Data, table(group, task_type, time.))[,,1]

bb[] <- matrix(c("odd", "even", "even", "odd"), ncol = 2)
bb

# Output:
    task_type
group C    S   
  Com odd  even
  Sim even odd

相关问题