mercredi 11 avril 2018

R conditional for loop - search for values and combination of values in data frame

I'm somewhat new to for loops and can't get my code to work properly despite reading a bunch of posts and tutorials. I want to write a loop that searches for a specific value in a column and returns a risk description, which is then added as a new row to the original data frame.

Here is an example data frame:

HR data frame

Repeat<-c("First","Second","Second","First","Second","Second")
Risk<-c(50,20,70,40,80,20)

df1<-data.frame(Repeat,Risk)

I need the loop to return "HR" if the risk column contains either the values 88, 55 or 50. If the risk column contains the value 80 or both 20 and 70, the loop needs to return "MR". If neither of the above-mentioned conditions is TRUE, the loop should return "LR". I've been stuck on this for a while and really would appreciate the help. Thank you.

my_vector = c()
for (i in df1$Risk){
  if (i %% 50)
    next
  my_vector[length(my_vector)+1] = "HR"
}

new_row<-c("Result",my_vector)
final<-rbind(df1,new_row)

Additional data frames

MR data frame

Repeat<-c("First","Second","Second","First","Second","Second")
Risk<-c(00,20,70,40,80,20)
df2<-data.frame(Repeat,Risk)

LR data frame

Repeat<-c("First","Second","Second","First","Second","Second")
Risk<-c(00,20,00,40,20,20)
df3<-data.frame(Repeat,Risk)

Aucun commentaire:

Enregistrer un commentaire