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

running multiples commands in one condition in r

I have a condition and I would like two things two happen in case the condition is met. When I put them in a single if..else statement the code does not give me the desired output. But when I run them separately it works. Can you please tell me what is wrong?
What I aim to do in the first part is to create a new column called id and then use this column as row names.

data1 <- lapply(data, function(y) {
  lapply(y, function(z) {
    if(all(c("variable", "missing") %in% names(z))) {
      z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number()))
      } else z
  })
})

data2 <- lapply(data1, function(y) {
  lapply(y, function(z) {
    if(all(c("variable", "missing") %in% names(z))) {
      `rownames<-`(z, z[["id"]])
      } else z
  })
})

This is the single statement version which doesn’t work:

data1 <- lapply(data, function(y) {
      lapply(y, function(z) {
        if(all(c("variable", "missing") %in% names(z))) {
        z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number()));
          `rownames<-`(z, z[["id"]])
          } else z
      })
    })

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

>Solution :

z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number())) works as a one-liner because its result will be implicitly returned by the function. However, because you don’t assign the result with <- the change is not saved, so when you have multiple lines you need to use <-, change it to z <- z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number())) and it will work in the multi-line statement.

data1 <- lapply(data, function(y) {
      lapply(y, function(z) {
        if(all(c("variable", "missing") %in% names(z))) {
          ## simplifying paste per r2evans's comment
          z <- z %>% mutate(id = paste0(z[["variable"]], "_", row_number()))
          ## I'd switch your row-names to a normal assignment for readability
          rownames(z) <- z[["id"]]
          ## the last thing will be returned
          z
        } else z
      })
    })
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