如何使用 if/then 语句有条件地替换 r 数据框中的值 [英] How to conditionally replace values in r data frame using if/then statement
问题描述
我想学习如何使用 if/then 语句有条件地替换 R 数据框中的值.假设我有一个这样的数据框:
I'd like to learn how to conditionally replace values in R data frame using if/then statements. Suppose I have a data frame like this one:
df <- data.frame(
customer_id = c(568468,568468,568468,485342,847295,847295),
customer = c('paramount','paramount','paramount','miramax','pixar','pixar'));
我想做一些类似的事情,如果客户在 ('paramount','pixar') 中使 customer_id 为 99.否则什么都不做".我正在使用此代码,但它不起作用:
I'd like to do something along the lines of, "if customer in ('paramount','pixar') make customer_id 99. Else do nothing". I'm using this code, but it's not working:
if(df$customer %in% c('paramount','pixar')){
df$customer_id == 99
}else{
df$customer_id == df$customer_id
}
我收到一条警告消息,例如条件长度 > 1,并且只会使用第一个元素.并且这些值不会被替换.
I get a warning message such as the condition has length > 1 and only the first element will be used. And the values aren't replaced.
我也想知道如何使用逻辑运算符来执行类似的操作,如果customer_id >= 500000,用'fox'替换customer.否则,什么都不做.
I'd also like to know how to do this using logical operators to perform something like, "if customer_id >= 500000, replace customer with 'fox'. Else, do nothing.
在 SQL 中很容易做到,但在 R 中似乎无法弄清楚.
Very easy to do in SQL, but can't seem to figure it out in R.
我的感觉是我在某处缺少一个括号?
My sense is that I'm missing a bracket somewhere?
如何使用 if/then 语句有条件地替换 R 数据框中的值?
How do I conditionally replace values in R data frame using if/then statements?
推荐答案
你可以使用ifelse
,像这样:
df$customer_id <- ifelse(df$customer %in% c('paramount', 'pixar'), 99, df$customer_id)
语法很简单:
ifelse(condition, result if TRUE, result if FALSE)
这是矢量化的,因此您可以在数据框列上使用它.
This is vectorized, so you can use it on a dataframe column.
这篇关于如何使用 if/then 语句有条件地替换 r 数据框中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!