dimanche 31 mars 2019

R: changing some column values, but not all, based on other column's values: problems with ifelse() and if(){}

I want to change certain values in one column (B) if a certain value appears in another column (A) but otherwise for the column values to remain unchanged. For example, in the following simplified version of my data I want to change the value in column B to be "0" if the value in column A is "none" otherwise I want the values in column B to remain unchanged

df <- data.frame(ID=c(1:4),A=c("1/wk","none","1/mo","1/wk"),B=c("3",NA,NA,"depends"))
    > df
      ID    A       B
    1  1 1/wk       3
    2  2 none    <NA>
    3  3 1/mo    <NA>
    4  4 1/wk depends

I tried this

df$B <- ifelse(df$A == "none","0",df$B)
    > df
      ID    A    B
    1  1 1/wk    1
    2  2 none    0
    3  3 1/mo <NA>
    4  4 1/wk    2

While this does change ID 2 to "0" in column B (which I want), it also changes the other values in column B. I want my output to look like this:

> df
  ID    A       B
1  1 1/wk       3
2  2 none       0
3  3 1/mo    <NA>
4  4 1/wk depends

I also tried to use if(){} but can't figure out how to use it when there are multiple columns involved

I am not particular about what function to use (though I prefer answers that use base R). PS - while I have found similar questions on stackoverflow none of the answers have worked for me.

Aucun commentaire:

Enregistrer un commentaire