问题
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"
Warning message:
In if (gsample$MAKE == "HOLDEN") gsample$Continent = "AUS" :
the condition has length > 1 and only the first element will be used
回答1:
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'
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']
NOTE: We assumed that the 'Continent' column is character
class.
回答2:
gsample$Continent <- ifelse(gsample$MAKE == "HOLDEN", "AUS","US")
回答3:
Assume that you want to change the value of a one column based on a value of a value in other column. Use following;
df$Continent[df$MAKE == 'HOLDEN'] <- 'AUS'
This will replicate all the values in the dataferame very quickly.
来源:https://stackoverflow.com/questions/32578082/r-how-to-replace-value-of-a-variable-conditionally