SPS SPS - 10 days ago 5
R Question

How to do conditional replace value in data

I have below data table and want to replace other than Web,Mobile usage into another category say others. (OR)
Is there anyway group the usage as Web, Mobile and rest all as others without replace the value like Web is used 1 , Mobile 1 and Others - 4 (OR)

Do we need to write a function to do so.

Id Name Usage
1 AAA Web
2 BBB Mobile
3 CCC Manual
4 DDD M1
5 EEE M2
6 FFF M3

Answer

Assuming that the 'Usage' is character class, we can use %chin% to create a logical index, negate it (!) and assign (:=) values in 'Usage' to 'Others'. This would be more efficient as we are assigning in place without any copying.

library(data.table)
setDT(df1)[!Usage %chin% c("Web", "Mobile"), Usage := "Others"]
df1
#   Id. Name  Usage
#1:   1  AAA    Web
#2:   2  BBB Mobile
#3:   3  CCC Others
#4:   4  DDD Others
#5:   5  EEE Others
#6:   6  FFF Others