Update subset of values in a dataframe column

ぐ巨炮叔叔 提交于 2019-11-27 06:30:25

问题


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)


来源:https://stackoverflow.com/questions/42706372/update-subset-of-values-in-a-dataframe-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!