I have an R framework called mydata that counts people with a certain age and a certain height. Thus, within the data, I have the variables mydata$ageto10 (= the number of people under the age of ten), mydata$ageto20 (= the number of people under the age of twenty), etc. Ages 35, 42, and 65. The same goes for height (and several other variables).
I want to create new variables that refer to the number of people aged 10 to 25 years, the age range from 25 to 35, from 35 to 42 and from 42 to 65. Therefore, for the first case, I want:
mydata$age10to25 <- mydata$ageto25 - mydata$ageto10
This works, but I want to do it in all ranges and do the same for height and other variables. There should be an easier way than copying these 40 times and changing variable names manually! :)
I thought it should be something like this:
for (i in c("age", "height")) { for (k in c(10,20,35,42, 65)) { assign(paste("mydata$", i, k, "to", <<next k here>>, sep=""), get(paste("mydata$", i, <<next k here>>, , sep="")) - get(paste("mydata$", i, k, , sep="")) } }
But obviously this does not work (even if I fill in k manually, it seems that the assign command is not intended to assign variable names to current data.
What is the best way to do this?