Search code examples
rreshapedcast

Extract column data on the basis of another column levels in r


My data looks like below: Column 1 is binary variable and column 2 is continuous variable.

Col1    Col2
0       21
0       34
1       36
0       24
1       96
.       .
.       .
0       25

And so on. I want my output in new data frame where column 1 levels as two new different columns("0" and "1") and corresponding column 2 values below both. Here is a reproducible example:

set.seed(77)
Col1 <- sample(c(0,1), 50, replace = TRUE)
Col2 <- round(rnorm(50),2)
dat <- data.frame(Col1, Col2)

So, basically my output should look like:

   "0"    "1"
   21     36
   34     96              
   24     .              
    .     .
    .     .
   25    

Solution

  • Conducting a t.test in R. It is best practice to convert your factor variable (the 0/1) to a factor before running the t.test. The function assumes each row is a separate person, and they belong to the group specified in Col1.

    Col1 <- sample(c(0,1), 50, replace = TRUE)
    Col2 <- round(rnorm(50),2)
    dat <- data.frame(Col1, Col2)
    
    dat$Col1 <- factor(dat$Col1) 
    t.test(Col2 ~ Col1, data = dat)