r:有条件地替换列子集中的值 [英] r: conditionally replace values in a subset of columns
本文介绍了r:有条件地替换列子集中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框:
I have a dataframe like so:
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
我想有条件地更换基于变量体育和合同开始的[4:6]列包含NA。
例如:
I would like to conditionally replace the columns [4:6] with NAs, based on the variables "sport" and "contract start". So for instance:
i1 <- which(df$sport =="basket" & df$contract_start>="2014-01-01")
将对我的条件所在的所有行进行索引遇见。
是否有一段简单的代码可以添加到上述代码中,在上述条件下,它将用NA替换df [4:6]?
我想结束这样的事情:
will index all the rows in which my conditions are met. Is there an easy piece of code to add to the above, that will replace df[4:6] with NAs given the above conditions? I would like to end up with something like that:
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
谢谢!
A。
Thanks! A.
推荐答案
您只需指定要用NA替换的行和列,然后进行分配 NA
:
You can simply specify the rows and columns that you would like to replace with NA, and assign NA
to it:
df[df$sport =="basket" & df$contract_start>="2014-01-01", 4:6] <- 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
这篇关于r:有条件地替换列子集中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文