R How to replace value of a variable conditionally

谁说胖子不能爱 提交于 2021-01-18 04:55:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!