Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create two columns based on some criteria in R

The data I have is almost similar to the data below.


A=01-03
B=04-06
C=07-09
D=10-11

      data<-read.table (text=" ID   Class   Time1   Time2   Time3
        1   1   1   3   3
        2   1   4   3   2
        3   1   2   2   2
        1   2   1   4   1
        2   3   2   1   1
        3   2   3   2   3
        1   3   1   1   2
        2   2   4   3   1
        3   3   3   2   1
        1   1   4   3   2
        2   1   2   2   2
        3   2   1   4   1
    
        ", header=TRUE)

I want to create 2 columns right after the Class column, i.e. the Bin and Zero columns based on A, B, C and D and IDs.
Therefore A goes to IDs 1,2, and 3. B goes to the next IDs, i.e., 1,2 and 3, and C goes to the next IDs, i.e., 1,2,3 and so on. Column Zero gets only numbers zeros. So the outcome would be:


     ID Class   Bin Zero    Time1   Time2   Time3
        1   1   01-03   0   1   3   3
        2   1   01-03   0   4   3   2
        3   1   01-03   0   2   2   2
        1   2   04-06   0   1   4   1
        2   3   04-06   0   2   1   1
        3   2   04-06   0   3   2   3
        1   3   07-09   0   1   1   2
        2   2   07-09   0   4   3   1
        3   3   07-09   0   3   2   1
        1   1   10-11   0   4   3   2
        2   1   10-11   0   2   2   2
        3   2   10-11   0   1   4   1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Please try the below code

library(tidyverse)

#use character vector with quotes
A='01-03'
B='04-06'
C='07-09'
D='10-11'

data<-read.table (text=" ID   Class   Time1   Time2   Time3
    1   1   1   3   3
    2   1   4   3   2
    3   1   2   2   2
    1   2   1   4   1
    2   3   2   1   1
    3   2   3   2   3
    1   3   1   1   2
    2   2   4   3   1
    3   3   3   2   1
    1   1   4   3   2
    2   1   2   2   2
    3   2   1   4   1

    ", header=TRUE)

#create a separate dataframe with bin column
data2 <- data.frame(bin=c(rep(A,3),rep(B,3),rep(C,3),rep(D,3))) 

data3 <- bind_cols(data, data2) %>% mutate(zero=0)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading