You can do something like the following:
df <- structure(list(var1 = c(1, 2, 3, 4),
var2 = c(1, 2, 3, 4),
var3 = c(1,2, 3, 4),
var4 = c(1, 2, 3, 4),
other_var1 = c(1, 0, 1, 0),
other_var2 = c(0,1, 0, 1),
other_var3 = c(1, 1, 0, 0),
other_var4 = c(0, 0, 1,1)),
class = "data.frame",
row.names = c(NA, -4L))
# var1 var2 var3 var4 other_var1 other_var2 other_var3 other_var4
# 1 1 1 1 1 1 0 1 0
# 2 2 2 2 2 0 1 1 0
# 3 3 3 3 3 1 0 0 1
# 4 4 4 4 4 0 1 0 1
## Values to replace based on OP original question
a <- 777
b <- 1
## Iter along all four variables avaible in df
for (i in 1:4) {
df <- within(df, {
assign(paste0("var",i), ifelse(get(paste0("other_var",i)) %in% c(b), ## Condition
a, ## Value if Positive
get(paste0("var",i)) )) ## Value if Negative
})
}
which results in the following output:
# var1 var2 var3 var4 other_var1 other_var2 other_var3 other_var4
# 1 777 1 777 1 1 0 1 0
# 2 2 777 777 2 0 1 1 0
# 3 777 3 3 777 1 0 0 1
# 4 4 777 4 777 0 1 0 1
The solution doesn't look like a one-line-solution, but it actually is one, a quite dense one tho; hence let's see how it works by its foundation components.
within()
: I don't want to repeat what other people have excellently explained, so for the within()
usage, I gently refer you here.
The: assign(paste0("var",i), X)
part.
Here I am following that @han-tyumi did in his answer, meaning recover the name of the variables using paste0()
and assign them the value of X
(to be explained) using the assign()
function.
Let's talk about X
.
Before I referenced assign(paste0("var",i), X)
. Where, indeed, X
is equal to ifelse(get(paste0("other_var",i)) %in% c(b), a, get(paste0("var",i)) )
.
Inside the ifelse()
:
The condition:
First, I recover the values of variable other_var(i)
(with i = 1,2,3,4) combining the function get()
with paste0()
while looping. Then, I use the %in%
operator to check whether the value assigned to variable b
(on my example, the number 1) was contained on variable other_var(i)
or not; this generates a TRUE or FALSE depending if the condition is met.
The TRUE
part of the ifelse()
function.
This is the simplest part if the condition is met then assign, a
(which in my example is equal to 777
).
The FALSE
part of the ifelse()
function.
get(paste0("var",i))
: which is the value of the variable itself (meaning, if the condition is not meet, then keep the variable unaltered).