0

I am trying to learn more about R loops and I want to convert the following Stata loop to R:

generate newvar=0

forvalues i=1/25 {
    replace newvar=1 if PR`i'=="8512" | PR`i'=="8521"  
}

Reading other posts wasn't as clear to me, hence this new post.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
TimF
  • 121
  • 2
  • 8
  • So you are trying to replace instances where newvar is one and PR[i] is either 8512 or 8521? Also would this be in a data frame? – Elin Jun 28 '18 at 01:46
  • https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/help/how-to-ask – r2evans Jun 28 '18 at 02:02
  • Hi Elin, yes those values are in the data frame. There are a series of PR values, PR1-PR25 and for each one I want to search for matching number and if it is of interest, classify a new variable. – TimF Jun 28 '18 at 13:57

1 Answers1

0

Here's a slightly contrived example. Stata:

sysuse auto
generate newvar = 0
generate rep79 = rep78
forvalues i = 78/79 {
  replace newvar = 1 if rep`i'==3 | rep`i'==4 
}
quietly sum newvar
di r(mean)
.64864865

R:

d <- foreign::read.dta("http://www.stata-press.com/data/r9/auto.dta")
d$newvar <- 0
d$rep79 <- d$rep78
for (i in 78:79) {
  d$newvar <- replace(d$newvar, d[[paste0("rep", i)]] %in% c(3, 4), 1)
}
mean(d$newvar)
# [1] 0.6486486
Weihuang Wong
  • 12,868
  • 2
  • 27
  • 48
  • Thanks weihuang. Can you explain the d[[ ]] portion of this? What is that doing in this? is is possible to add something like d[[paste0("rep", i)]] %in% c(3, 4) & d[[paste0("trunk")]] %in% c(11, 12) to make the selection even more conditional? – TimF Jul 03 '18 at 19:36
  • For your first question see https://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis. For the second question, the short answer is "yes", but if you have follow-ups I'd suggest opening a new question since SO comments are not really set up for extended discussion. – Weihuang Wong Jul 03 '18 at 23:40