jeudi 26 avril 2018

How to apply a "for loop" in all columns in R?

I have this data and a for that I created to convert all the elements in a column, based on condition (if). (I know that there are more ways to do that...)

Here it is:

S1 <- c(0,1,1,0,0,2,2,1,1,1,1,1,0)
S2 <- c(2,1,0,1,0,2,1,1,0,1,2,2,1)
S3 <- c(0,1,0,0,1,2,0,1,2,1,2,0,2)
S4 <- c(2,1,0,2,1,2,2,1,2,1,2,2,0)

df <- data.frame(S1,S2,S3,S4)

for (i in 1:nrow(df)){
  if(df[i,1] == 0){
    df[i,1] <- "A/A"
  }
  if(df[i,1] == 1){
    df[i,1] <- "A/T"
  }
  if(df[i,1] == 2){
    df[i,1] <- "T/T"
  }
  if(df[i,1] == "NaN"){
    df[i,1] <- 0
  }
}

This is the actual:

S1  S2  S3  S4
0   2   0   2
1   1   1   1
1   0   0   0

When I run the for it works for the first column only, since I described the df[i,1]. The question is, how can I do this for all columns simultaneously? Is there a way I could solve this problem?

Thanks

Aucun commentaire:

Enregistrer un commentaire