Search code examples
rdataframefor-loopif-statementrscript

How can I create a column for a dataframe where values are dependent on the values of another column?


I have been trying to create a column for a dataframe where each new observation depends on the value of the observations of other columns. I tried to come up with code that would do that but haven't been any lucky

I also checked these answers ) but couldn't make them work if anyone has an idea on how to do it I would be truly grateful

    for (dff$prcganancia in dff){ 
     if(dff$grupo == 1){
      prcganancia == 0.3681
     }elseif(dff$grupo == 2){
      prcganancia == 0.2320
     }elseif(dff$grupo == 3){
      prcganancia == 0.2851
     }elseif(dff$grupo == 4){
      prcganancia == 0.4443
     }elseif(dff$grupo == 5){
      prcganancia == 0.3353
     }elseif(dff$grupo == 6){
      prcganancia == 0.2656
     }elseif(dff$grupo == 7){
      prcganancia == 0.2597
     }elseif(dff$grupo == 8){
      prcganancia == 0.2211
     }elseif(dff$grupo == 9){
      prcganancia == 0.3782
     }elseif(dff$grupo == 10){
      prcganancia == 0.3752}
     }

What my lousy code is trying to do is make the observation for prcganancia where grupo equals to 1, 0.3681 (every obsrvation where grupo == 1 the observation for prcganancia == 0.3681) and so on


Solution

  • Try dplyr::recode(). You can pass either "old value = new value" pairs:

    set.seed(13)
    library(dplyr)
    
    dff <- data.frame(grupo = sample(10, 10))
    
    dff$prcganancia <- recode(
      dff$grupo,
      `1` = 0.3681, 
      `2` = 0.2320, 
      `3` = 0.2851, 
      `4` = 0.4443, 
      `5` = 0.3353, 
      `6` = 0.2656, 
      `7` = 0.2597, 
      `8` = 0.2211, 
      `9` = 0.3782, 
      `10` = 0.3752
    )
    

    Or unnamed values, which will be matched by index:

    dff$prcganancia <- recode(
      dff$grupo,
      0.3681, 
      0.2320, 
      0.2851, 
      0.4443, 
      0.3353, 
      0.2656, 
      0.2597, 
      0.2211, 
      0.3782, 
      0.3752
    )
    

    Result:

       grupo prcganancia
    1      8      0.2211
    2      3      0.2851
    3     10      0.3752
    4      5      0.3353
    5      2      0.2320
    6      7      0.2597
    7      6      0.2656
    8      4      0.4443
    9      9      0.3782
    10     1      0.3681