更新数据框列中的值子集

问题描述 投票:1回答:1

这是我的数据帧的摘录:

  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

我需要更新第一列,以便每个数字减去1,但仅限于条件a和b。也就是说,而不是c(4, 15, 17, 11, 8, 12, 10, 17, 12, 15),我会得到c(3, 14, 16, 10, 7, 12, 10, 17, 12, 15)

r dataframe replace subset
1个回答
1
投票

可以在这里使用ifelse。假设数据框名为df1

df1$x <- ifelse(df1$y %in% c("a", "b"), df1$x - 1, df1$x)
© www.soinside.com 2019 - 2024. All rights reserved.