Home > Enterprise >  Add the parent value as column in R dataset
Add the parent value as column in R dataset

Time:09-28

I am not quite sure how to phrase the problem statement. I am trying this out in RStudio but got no clue how to get it done.

I want to add a new column that will tell me the level 1 for each of the level 2 equipments.

This is how my dataset looks like,

equipment <- c("cleats","whistle","Football","Bat","Pink Ball","Cricket")
level <- c(2,2,1,2,2,1)
dt <- cbind(equipment,level) 

CodePudding user response:

If level always be like 2, 2, 1, 2, 2, 1, you may try this.

for (i in c(dim(dt)[1]:1)){
  if (dt$level[i] == 1){
    key <- dt$equipment[i]
    
  } else {}
  if (dt$level[i] == 2){
    dt$newcol[i] <- key
  } else{
    dt$newcol[i] <- NA
  }
}

  equipment level   newcol
1    cleats     2 Football
2   whistle     2 Football
3  Football     1     <NA>
4       Bat     2  Cricket
5 Pink Ball     2  Cricket
6   Cricket     1     <NA>

For rows with level == 2, I didn't handle that yet. If some other actions needed to that rows, please let me know.

CodePudding user response:

You can use fill:

library(tidyverse)

equipment <- c("cleats","whistle","Football","Bat","Pink Ball","Cricket")
level <- c(2,2,1,2,2,1)
dt <- data.frame(equipment,level)

dt %>%
  mutate(level_combined = if_else(level == 1, equipment, NA_character_)) %>%
  fill(level_combined, .direction = 'up')

which gives:

  equipment level level_combined
1    cleats     2       Football
2   whistle     2       Football
3  Football     1       Football
4       Bat     2        Cricket
5 Pink Ball     2        Cricket
6   Cricket     1        Cricket
  •  Tags:  
  • r
  • Related