[R] R code for if-then-do code blocks

Paul Miller pjmiller_57 @ending from y@hoo@com
Mon Dec 17 16:27:51 CET 2018


Hello All,

Season's greetings!

 Am trying to replicate some SAS code in R. The SAS code uses if-then-do code blocks. I've been trying to do likewise in R as that seems to be the most reliable way to get the same result. 

Below is some toy data and some code that does work. There are some things I don't necessarily like about the code though. So I was hoping some people could help make it better. One thing I don't like is that the within function reverses the order of the computed columns such that test1:test5 becomes test5:test1. I've used a mutate to overcome that but would prefer not to have to do so. 

 Another, perhaps very small thing, is the need to calculate an ID variable that becomes the basis for a grouping. 

I did considerable Internet searching for R code that conditionally computes blocks of code. I didn't find much though and so am wondering if my search terms were not sufficient or if there is some other reason. It occurred to me that maybe if-then-do code blocks like we often see in SAS as are frowned upon and therefore not much implemented. 

I'd be interested in seeing more R-compatible approaches if this is the case. I've learned that it's a mistake to try and make R be like SAS. It's better to let R be R. Trouble is I'm not always sure how to do that. 

Thanks,

Paul


d1 <- data.frame(workshop=rep(1:2,4),
                gender=rep(c("f","m"),each=4))

library(tibble)
library(plyr)

d2 <- d1 %>%
  rownames_to_column("ID") %>%
  mutate(test1 = NA, test2 = NA, test4 = NA, test5 = NA) %>%
  ddply("ID",
        within,
        if (gender == "f" & workshop == 1) {
          test1 <- 1
          test1 <- 6 + test1
          test2 <- 2 + test1
          test4 <- 1
          test5 <- 1
        } else {
          test1 <- test2 <- test4 <- test5 <- 0
        })



More information about the R-help mailing list