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

编程入门 行业动态 更新时间:2024-10-08 01:23:40
本文介绍了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:有条件地替换列子集中的值

本文发布于:2023-11-22 08:07:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616614.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列子   有条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!