如何使用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'));
我想做些类似的事情, 如果in('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'替换客户.否则,什么也不做.
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
,如下所示:
You can use ifelse
, like this:
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屋!