0

I have a tedious task, that I would like to outsource to R. I thought about a loop, that does the same for every wave ( "99" to "16"). Basically, whenever there is a 99 in the code below, I would like to adapt this for every wave.

I am used to STATA, where I would simply to this with replacing 99 with `wave' and use a foreach loop. Is there a simple way to do this in R? How can I reference a string in a loop?

Otherwise it might just be a "copy-paste"-task :-) Thanks a lot for your help!

`wave <- ("99", "00", "01", "02", "03", "04")`



names(m99) <- gsub("(^x99)|(^h99)|(^i99)|(^weih99)", "", names(m99))
names(m99) <- gsub("99$", "", names(m99))
names(m99) <- paste(names(m99), "h", sep="_")
m99$idhous <- m99$idhous_h 

p99 <- list_files_p[[1]]
names(p99)
names(p99) <- gsub("(^p99)|(^i99)|(^weip99)","", names(p99))
names(list_files_p[[1]]) <- gsub("99$","", names(list_files_p[[1]]))
p99[,grep("^x",names(p99))] <-  NULL
names(p99) <- paste(names(p99), "p", sep="_")
names(p99)
sort(table(names(p99)))
p99$idhous <- p99$idhous_p

pm99 <- left_join(p99, m99, by="idhous")
  • Do you mean you have other objects named `m00`, `m01` etc that you need to loop through, in addition to switching the `99` out of the regexes? – joran May 04 '18 at 15:22
  • 1
    Please make this question more [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by showing us what `m99` (and perhaps `p99`) looks like, otherwise it's a complete shot in the dark. (I suggest `dput(head(m99,n=10))` or some other `n=` number that provides a representative form of `m99`. The impetus for using `dput` is so that we can copy and paste *the true structure of the object*, whereas showing its representation on the R console is insufficient.) – r2evans May 04 '18 at 15:22
  • Right I have other objects (df) m99 - m16 with the "99" string, and in this objects I also have to make changes to variable names (e.g. delete the "99", "01" etc out of it). – Patrick May 04 '18 at 15:30
  • Ok, so we do things very differently in R than in STATA. Having lots of related objects stored separately in R is extremely inconvenient and dealing with that generally leads to frustration. In R we put related data objects in _named lists_. So you have a list called `m`, with elements `m99`, `m00`, etc. And so on. If you're new to R I would start with just a for loop that then indexes those lists. You can build the regexes as needed with `paste`. – joran May 04 '18 at 15:32
  • That is true, a different thinking is needed :-) Thanks, a lot! If I am in a list, how can do the changes in the variable names for every item. E.g. to get rid of the "99" in the first element of the list, "00" for the second ... ? So that it does the code beneath automatic: names(m99) <- gsub("(^x99)|(^h99)|(^i99)|(^weih99)", "", names(m99)) – Patrick May 04 '18 at 15:44

0 Answers0