0

Using my Data, I was wondering if there is a way to achieve my Desired_output (an object of class table or matrix)?

I tried the following without success:

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
  " 
Simon Harmel
  • 927
  • 2
  • 9
  • 1
    Your desired output is just a long string. Did you intend for this, or did you mean something else, such as wrapping the string in `read.table`? Could you please edit to clarify? – jpsmith Jan 03 '23 at 22:00
  • @jpsmith, an object of class `table` or `matrix`. – Simon Harmel Jan 03 '23 at 22:07
  • 1
    Your description of your desired output is insufficient. As well as the class of the object, you need to define its properties. As has already been said, do you want to convert your `Desired_output` character string to a table or matrix, or does it in some was describe the contents of your desired output? Your specification is ambiguous. – Limey Jan 03 '23 at 22:19
  • @Limey, that is my question, I'm asking what operation is needed for my `Data` to look like the output which can be either of class matrix or table. – Simon Harmel Jan 03 '23 at 22:26

2 Answers2

1

Perhaps:

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 
Simon Harmel
  • 927
  • 2
  • 9
  • If this is what you are after you can optimize your code in a single line with `bb[] <- matrix(c("odd", "even", "even", "odd"), ncol = 2)` – jpsmith Jan 04 '23 at 02:00
1

We may get the distinct rows before reshaping to 'wide' with pivot_wider and converting to table

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]

-output

> out
     task_type
group S    C   
  Sim odd  even
  Com even odd 
akrun
  • 874,273
  • 37
  • 540
  • 662