[R] Loop over columns of dataframe and change values condtionally

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Thu Sep 2 15:35:24 CEST 2021


Hello,
it is possible to select the columns of a dataframe in sequence with:
```
for(i in 1:ncol(df)) {
  df[ , i]
}
# or
for(i in 1:ncol(df)) {
  df[ i]
}
```
And change all values with, for instance:
```
for(i in 1:ncol(df)) {
  df[ , i] <- df[ , i] + 10
}
```
Is it possible to apply a condition? What would be the syntax?
For instance, to change all 0s in a column to NA would `df[i][df[i ==
0] = NA` be right?
Thank you


-- 
Best regards,
Luigi



More information about the R-help mailing list