Update subset of values in a dataframe column

2020-02-01 06:30发布

问题:

Here's an excerpt of my dataframe:

  x         y     se
  4         a     7.146329
 15         a     8.458633
 17         a     9.286849
 11         b     6.700024
  8         b     4.697962  
 12         c     7.884244
 10         c     7.834816
 17         c     7.762385
 12         d     5.910785
 15         d     12.98158

I need to update the first column, so that each number will be subtracted by 1, but only for conditions a and b. That is, instead of c(4, 15, 17, 11, 8, 12, 10, 17, 12, 15), I would get c(3, 14, 16, 10, 7, 12, 10, 17, 12, 15).

回答1:

Could use ifelse here. Assuming data frame is named df1:

df1$x <- ifelse(df1$y %in% c("a", "b"), df1$x - 1, df1$x)