[R] Repeating the same calculation across multiple pairs of variables

Joshua Wiley jwiley.psych at gmail.com
Sat Mar 5 04:00:16 CET 2011


Hi Al,

Assuming that the order of the matrices resulting from selecting
"avars" and "bvars" is identical (it is at least in the example you
gave), then you can do:

dat <- data.frame(a1=1:10, a2=11:20, a3=21:30, b1=101:110, b2=111:120,
b3=121:130)

avars <- paste("a", 1:3, sep = '')
bvars <- paste("b", 1:3, sep = '')
cvars <- paste("c", 1:3, sep = '')

dat[, cvars] <- dat[, avars] / dat[, bvars]

If you are using character strings for the names, you need to use [
rather than $.  For documentation, see ?"["

Hope this helps,

Josh

On Fri, Mar 4, 2011 at 4:37 PM, Al Roark <hrbuilder at hotmail.com> wrote:
>
> Hi all,
>
> I frequently encounter datasets that require me to repeat the same calculation across many variables. For example, given a dataset with total employment variables and manufacturing employment variables for the years 1990-2010, I might have to calculate manufacturing's share of total employment in each year. I find it cumbersome to have to manually define a share for each year and would like to know how others might handle this kind of task.
>
> For example, given the data frame:
>
> df<-data.frame(a1=1:10, a2=11:20, a3=21:30, b1=101:110, b2=111:120, b3=121:130)
>
> I'd like to append new variables--c1, c2, and c3--to the data frame that are the result of a1/b1, a2/b2, and a3/b3, respectively.
>
> When there are only a few of these variables, I don't really have a problem, but it becomes a chore when the number of variables increases. Is there a way I can do this kind of processing using a loop? I tried defining a vector to hold the names for the "c variables" (e.g. c1,c2, ... cn) and creating new variables in a loop using code like:
>
> avars<-c("a1","a2","a3")
> bvars<-c("b1","b2","b3")
> cvars<-c("c1","c2","c3")
> for(i in 1:3){
>  df$cvars[i]<-df$avars[i]/df$bvars[i]
> }
>
> But the variable references don't resolve properly with this particular syntax.
>
> Any help would be much appreciated. Cheers.
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list