Home > Software engineering >  Arranging a dataset by groups in R
Arranging a dataset by groups in R

Time:04-06

I need help trying to make a dataset which contains which treatment the participants are on and what they scored in a composite test (this is just an exercise for my course no real data used)

A <- c(36, 35, 22, 20)
B <- c(26, 30, 25, 20)
C <- c(42, 30, 45, 62)

treatment <- c("A", "B", "C")

depression <- c(A, B, C)

df1 <- data.frame(treatment, depression)

It arranges the data in the dataframe wrong with each value being A, B, C instead of A, A , A , A, B...

anyone know how to convert and arrange this data?

I need the data arranged so I can split and do different calculations with them.

CodePudding user response:

treatment <- rep(LETTERS[1:3], each=4)
depression <- c(A, B, C)
df1 <- data.frame(treatment, depression)

CodePudding user response:

I think you're looking for

df1 <- data.frame(treatment = rep(treatment, each = 4), depression)

For production/"real-life" code you would probably want to do something fancier, e.g.

L <- tibble::lst(A,B,C)  ## self-naming list
data.frame(treatment = rep(names(L), lengths(L)),
           depression = unlist(L))

CodePudding user response:

Here is tidyverse approach:

library(tidyverse)

tibble(depression) %>% 
  mutate(treatment = rep(treatment, each=length(A)))
   depression treatment
        <dbl> <chr>    
 1         36 A        
 2         35 A        
 3         22 A        
 4         20 A        
 5         26 B        
 6         30 B        
 7         25 B        
 8         20 B        
 9         42 C        
10         30 C        
11         45 C        
12         62 C  
  •  Tags:  
  • r
  • Related