I have an R dataframe called mydata with the counts of people with a certain age and certain height. So within the dataframe I have variables mydata$ageto10 (=the number of people up to ten years of age), mydata$ageto20 (=the number of people up to twenty years of age), and so on with the ages 35, 42, and 65. Same goes for height (and a couple of other variables).
I want to create new variables which refer to the count of the number of people within the age range 10to25, the age range 25to35, 35to42, and 42to65. So for the first case, I want to do:
mydata$age10to25 <- mydata$ageto25 - mydata$ageto10
This works, but I want to do this across all ranges, and do the same for height and the other variables. There must be an easier way than copy-pasting this 40 times and changing the 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 doesn't work (even if I fill in the k by manually, it seems the assign command is not meant for assigning variable names to the current data.
What's the best way to do this?