Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional sapply in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading