mercredi 18 septembre 2019

Iterating through data frame and changing values on condition [R]

Had to make an account because this sequence of for loops has been annoying me for quite some time.

I have a data frame in R with 1000 rows and 10 columns, with each value ranging from 1:3. I would like to re-code EVERY entry so that: 1==3, 2==2, 3==1. I understand that there are easier ways to do this, such as sub-setting each column and hard coding the condition, but this isn't always ideal as many of the data sets that I work with have up to 100 columns.

I would like to use a nested loop in order to accomplish this task -- this is what I have thus far:

for(i in 1:nrow(dat_trans)){
  for(j in length(dat_trans)){
    if(dat_trans[i,j] == 1){
      dat_trans[i,j] <- 3
    } else if(dat_trans[i,j] == 2){
      dat_trans[i,j] <- 2
    } else{
      dat_trans[i,j] <- 1
    }
  }
}

So I iterate through the first column, grab every value and change it based on the if/else's condition, I am still learning R so if you have any pointers in my code, feel free to point it out.

edit: code

Aucun commentaire:

Enregistrer un commentaire