4

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?

1 Answer 1

6

I presume you are a refugee from another statistical package (stata perhaps or SAS). You can't use assign to assign to columns using $ and paste. In general if you are using assign for a standard task, you are doing something that is not idiomatically R, or there are better solutions.

something like

lower <- c(10,25,35,42)
upper <- c(25,35,42,65)

# create the differences
newData <-   myData[,paste0('ageto',upper)] - myData[, paste0('ageto',lower)]
# name them with valid names (not starting with numbers
names(newData) <- paste0('from',lower,'to',upper)
# add as columns to the original
myData <- cbind(myData, newData)

No loops required!

Sign up to request clarification or add additional context in comments.

2 Comments

No way, that's awesome! Thanks! (PS. Yes, refugee from Stata ;-) I'm loving R more and more every day)
@user1780218 if that solves your problem, you should give the answer a tick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.