r:有条件地替换列子集中的值

时间:2016-07-25 18:40:01

标签: r replace conditional

我有一个像这样的数据框:

sport   contract start contract end visits spends purchases
basket   2013-10-01     2014-10-01   12      14      23
basket   2014-02-12     2015-03-03   23      11      7
football 2015-02-12     2016-03-03   23      11      7
basket   2016-07-17     2013-09-09   12       7      13

我想根据变量“sport”和“contract start”有条件地用NAs替换列[4:6]。 例如:

i1 <- which(df$sport =="basket" & df$contract_start>="2014-01-01")

将索引符合条件的所有行。 是否有一个简单的代码可以添加到上面,在给定上述条件的情况下,将用NAs替换df [4:6]? 我想最终得到类似的东西:

sport   contract start contract end visits spends purchases
basket   2013-10-01     2014-10-01   12      14      23
basket   2014-02-12     2015-03-03   NA      NA      NA
football 2015-02-12     2016-03-03   23      11      7
basket   2016-07-17     2013-09-09   NA      NA      NA

谢谢! 甲

2 个答案:

答案 0 :(得分:7)

您只需指定要用NA替换的行和列,并为其指定!important

NA

答案 1 :(得分:3)

library("data.table")
setDT(df)
df[i = sport == "basket" & contract_start >= "2014-01-01", 
   j = c("visits", "spends", "purchases") := NA]

> df
      sport contract_start contract_end visits spends purchases
1:   basket     2013-10-01   2014-10-01     12     14        23
2:   basket     2014-02-12   2015-03-03     NA     NA        NA
3: football     2015-02-12   2016-03-03     23     11         7
4:   basket     2016-07-17   2013-09-09     NA     NA        NA

使用my_cols变量的上述代码的变体:

my_cols <- names(df)[4:6]
df[i = sport == "basket" & contract_start >= "2014-01-01", 
   j = (my_cols) := .(NA)]