Reputation: 976
I have the below df
var1 var2 a1 a2
1 a b y z
2 b a z y
3 b b z z
created from the following code
help <- data.frame(var1 = c("a", "b", "b"), var2 = c("b", "a", "b"), a1 = c(y, z, z), a2 = c(z, y, z))
my intention is to create an ifelse statement where I am able to (1) replace all a1 values to 'bp' when var1 equals 'a', and (2) replace all a2 values to 'bp' when var2 equals 'a'. I do not want to change the value if var1 or var2 is not 'a'.
Is the ifelse command not the best way to solve this problem? I started doing each one manually using help$a1[help$a1 == "a"] <- "bp"
however, this will take a bit of time as I have multiple variables and a large dataset. Any assistance would be great.
Many thanks.
Upvotes: 0
Views: 314
Reputation: 26446
You can use standard subsetting. Assuming per question edit that a1
and a2
are of class "character", then
df
# var1 var2 a1 a2
#1 a b y z
#2 b a z y
#3 b d z z
df[,3:4][df[,1:2]=="a"]<-"bp"
df
# var1 var2 a1 b2
#1 a b bp z
#2 b a z bp
#3 b d z z
You can also take advantage of your naming convention for the same
sel<-paste0("var",1:2)
mut<-paste0("a",1:2)
df[,mut][df[,sel]=="a"]<-"bp"
In either case the inner part, e.g. df[,sel]=="a"
is returning a logical matrix the same shape as df[,sel]
(and hence the same shape as df[,mut]
), which is TRUE
where and only where there was an "a". The outer part, e.g. df[,mut][...]
, uses that logical matrix to indicate the subset subject to the assignment.
Upvotes: 1