R在多个条件下替换变量 [英] R replace variable given multiple conditions

查看:61
本文介绍了R在多个条件下替换变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据组织如下:

year    company color   car_total
2000    toyota  red     873
2013    honda   red     737
2012    nissan  green   809
2002    toyota  blue    429
2000    nissan  green   861
2012    honda   red     742
2009    toyota  red     320
2010    ford    yellow  319
2000    ford    green   587
2011    nissan  blue    777
2014    ford    blue    32

在给定多个条件的情况下,我试图替换列中的值.两种情况:

I am trying to replace the values in columns given multiple conditions. Two situations:

  1. 我想用0替换 company == ford company == nissan 的行中的每个 car_total .命令可以做到这一点?

  1. I would like to replace each car_total for rows of company == ford OR company == nissan with 0. What command would accomplish this?

如果我的约束来自不同的列怎么办?例如如果我想将其 company ==福特或 color ==红色的任何 car_total 替换为0,怎么办?

What if my constraints came from different columns? e.g. What if I wanted to replace any car_total which has its company == ford OR color == red with 0?

推荐答案

从注释中可以看出,这可以作为标准选择紧凑地完成.但是有时候逻辑向量使事情变得更清楚.

As you have seen from comments this can be done compactly as a standard selection. But sometimes logical vectors make things clearer.

假设您的数据框称为 df

redcars <- df$color == "red"
fords <- df$company == "ford"
ford_or_nissan = fords | df$company == "nissan" # or alternatively
ford_or_nissan = df$company %in% c("ford","nissan")

这为您提供了三个向量,可用于选择所需的行

This gives you three vectors you can use to select the desired rows

df$car_total[ford_or_nissan] <- 0
df$car_total[fords | redcars] <- 0

使用逻辑运算符,您可以根据需要构建复杂的选择.

With logical operators, you can build up as complex a selection as you want.

这篇关于R在多个条件下替换变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆