I am trying to apply conditional sapply to vectors as shown below
Basically, then the vector contains "input_" in the beginning, then apply some condition to LHS and RHS.
The condition is when there is "input_b", then RHS should be paste0(x, "d"), where LHS should be gsub("input_", "", x). Here RHS is working fine but not the LHS part. Refer expected output below
exp <- c("a", "input_b")
asd <- as.list(sapply(exp , function(x) {ifelse(substr(x, start = 0, stop = 5) == "input", assign(gsub("input_", "", x), paste0(x, "d")), assign(x, x))}))
asd
$a
[1] "a"
$input_b
[1] "input_bd"
Expected output
asd
$a
[1] "a"
$b
[1] "input_bd"
>Solution :
Use setNames instead of assign (sapply seems redundant, because exp is not a list):
exp_values <- ifelse(startsWith(exp, "input"),
paste0(exp, "d"),
exp)
exp_names <- ifelse(startsWith(exp, "input"),
gsub("input_", "", exp),
exp)
as.list(setNames(exp_values, exp_names))
Output:
$a
[1] "a"
$b
[1] "input_bd"
It is however still not clear to me what problem we’re solving exactly, so it might not be the most efficient way to solve the problem at hand.