0
votes

I need to create a group of variables based on the same criteria. The first variable is named location1, and is created based on other variables (var1, var2, var3) as:

location1[var1==1] <- 1
location1[var2==1] <- 2
location1[var3==1] <- 3
...
location2[var1==1] <- 1
location2[var2==1] <- 2
location2[var3==1] <- 3

I have 100 location variable to create, location1 to location100, all using the same criteria based on var1,var2, var3 as shown here. Instead of typing it 100 times, which is very silly, how can I simply the code? var1, var2, var3 are dichotomous 1/0 values.

1
Can you please share a bit of sample input? Just a few rows/values from var1, var2, and var3 should be enough to illustrate the problem. Also please clarify the difference between location1 and location2 -- the code you share for them is identical. - Gregor Thomas

1 Answers

0
votes

It would be much simpler if you could work with a matrix in which location is a variable along with var1, var2, and var3. For example:

all <- cbind(location=rep(1:100), var1=1, var2=2, var3=3)
all[1, ]
# location     var1     var2     var3 
#       1        1        2        3 

You would just access the values by using all[1, ] instead of location1 which makes it easier to process all of the locations at once using a for loop or the apply/sapply/lappy functions.