Home > other >  Combining two tables/arrays in R
Combining two tables/arrays in R

Time:01-04

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
  " 

CodePudding user response:

Perhaps:

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

bb[1,1] <- "odd"
bb[2,1] <- "even"
bb[1,2] <- "even"
bb[2,2] <- "odd"
bb

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

CodePudding user response:

Here is one way you can achieve the desired output:

Data %>% 
  group_by(group, task_type) %>% 
  summarize(time = paste(time., collapse = ", ")) %>% 
  spread(task_type, time)

This code will first group the data by group and task_type, then summarize the time column by concatenating the values into a single string, separated by a comma and a space. Finally, it will spread the resulting data frame so that the task_type values become columns.

This should give you a result similar to the following:

# A tibble: 2 x 3
  group time_C time_S
  <chr> <chr>  <chr> 
1 Com   1, 3   2, 4  
2 Sim   2, 4   1, 3 

If you want to change the column names to match your desired output, you can use the rename function:

Data %>% 
  group_by(group, task_type) %>% 
  summarize(time = paste(time., collapse = ", ")) %>% 
  spread(task_type, time) %>% 
  rename(C = time_C, S = time_S)

This should give you the following result:

 # A tibble: 2 x 3
  group C     S    
  <chr> <chr> <chr>
1 Com   1, 3   2, 4 
2 Sim   2, 4   1, 3 
  • Related