[R] R code for if-then-do code blocks
Gabor Grothendieck
ggrothendieck @ending from gm@il@com
Tue Dec 18 04:55:57 CET 2018
There is some discussion of approaches to this here:
https://stackoverflow.com/questions/34096162/dplyr-mutate-replace-on-a-subset-of-rows/34096575#34096575
On Mon, Dec 17, 2018 at 10:30 AM Paul Miller via R-help
<r-help using r-project.org> wrote:
>
> 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
> })
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list