Search code examples
rreshapecontrast

How to create a table like contrasts in r


I need help converting a dataframe with certain values into columns that looks like contrasts in R. For example.

code <- data.frame(code = c('R1111', 'R1112', 'R1111', 'R1111', 'R1113', 
                            'R1112', 'R1112', 'R1112', 'R1113', 'R1115')) 

I need to convert this to the following table

    code   R1111  R1112   R1113   R1115
1  R1111     1      0       0       0
2  R1112     0      1       0       0
3  R1111     2      0       0       0 
4  R1111     3      0       0       0 
5  R1113     0      0       1       0 
6  R1112     0      2       0       0 
7  R1112     0      3       0       0 
8  R1112     0      4       0       0 
9  R1113     0      0       2       0 
10 R1115     0      0       0       1 

I have 1400 rows with those sorts of codes that I need to convert. If you notice, each column with the code has increasing number. I tried to do this using reshape2, but i keep getting errors - meaning I haven't been able to figure this out. How can I get this result?


Solution

  • An option is to use mapply in combination with ifelse to get the desired result as:

    cbind(code,mapply(function(x){
      ifelse(code$code==x,cumsum(code$code==x),0)
    }, unique(as.character(code$code))))
    
    #     code R1111 R1112 R1113 R1115
    # 1  R1111     1     0     0     0
    # 2  R1112     0     1     0     0
    # 3  R1111     2     0     0     0
    # 4  R1111     3     0     0     0
    # 5  R1113     0     0     1     0
    # 6  R1112     0     2     0     0
    # 7  R1112     0     3     0     0
    # 8  R1112     0     4     0     0
    # 9  R1113     0     0     2     0
    # 10 R1115     0     0     0     1