Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201941

Loop over list of partial variable names in R

$
0
0

Absolute n00b here... moving over from Stata (where this would be easy):

I've got a dataset relating to a list of drugs, "alcohol", "cannabis", "tobacco", "mdma", "cocaine", "amphetamine", "lsd", etc.. in a dataframe, df.

Each one has variable ever used (ever_[drug]), used in year (year_[drug]), used in last month (mth_[drug]), which are answered sequentially. One would only be asked the about latter time frame if you answer "yes" (i.e. 2) to the previous. In each case "no" is 1. I need to recode into one overall variable, say, my_[drug].

This works for just one:

df$my_cannabis <-  ifelse(df$ever_cannabis == 1, 0, 
                ifelse(df$year_cannabis == 1, 1,
                ifelse(df$mth_cannabis == 1, 2, 3)))

How can I loop over all the drug names and generate my_[drug] for each?


Viewing all articles
Browse latest Browse all 201941

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>