R如何有条件地替换变量的值 [英] R How to replace value of a variable conditionally
问题描述
我确定这个问题已经被问到了一堆时间,但我找不到解决方案。
I am sure this question has been asked stacks of time but I couldn't find a solution.
我试图有条件地替换第二个变量的值基于第一个变量的值。这是数据。
I am trying to conditionally replace the value of a second variable based on the value of first variable. Here is the data.
MAKE Continent
1 HOLDEN US
2 HOLDEN US
3 FORD US
4 FORD US
if(gsample$MAKE == "HOLDEN") gsample$Continent = "AUS"
警告信息:
In if (gsample$MAKE == "HOLDEN") gsample$Continent = "AUS" :
the condition has length > 1 and only the first element will be used
推荐答案
基于逻辑条件 MAKE =='HOLDEN'
,如果条件为<,我们使用 ifelse
返回'AUS' code> TRUE 或者返回'Continent'的相应值。
Based on the logical condition MAKE=='HOLDEN'
, we use ifelse
to return 'AUS' if that the condition is TRUE
or else return the corresponding values of 'Continent'.
gsample$Continent <- with(gsample, ifelse(MAKE=='HOLDEN', 'AUS', Continent))
或者我们使用逻辑索引对大陆进行子集化并通过分配来替换它。
Or we use the logical index to subset the 'Continent' and replace that by assigning.
gsample$Continent[gsample$MAKE=='HOLDEN'] <- 'AUS'
或者我们可以使用 data.table
。我们根据 i $中的逻辑条件将'data.frame'转换为'data.table'(
setDT(gsample)
) c $ c>,我们将(:=
)大陆分配给'AUS'
Or we can use data.table
. We convert the 'data.frame' to 'data.table' (setDT(gsample)
), based on the logical condition in i
, we assign (:=
) the Continent to 'AUS'
library(data.table)
setDT(gsample)[MAKE=='HOLDEN', Continent:= 'AUS']
注意:我们假设'Continent'列是字符
class。
NOTE: We assumed that the 'Continent' column is character
class.
这篇关于R如何有条件地替换变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!