[R] Loop in variable names

jim holtman jholtman at gmail.com
Wed Feb 9 20:18:52 CET 2011


Try:

for(i in angus) {
 cut <- StoreData[[paste("P", i)]]
 table(StoreData$CompanyID, !is.na(cut))
 }

On Wed, Feb 9, 2011 at 1:02 PM, Rita Carreira <ritacarreira at hotmail.com> wrote:
>
>
> Hello!
> I would like to do some tables for several variables and I would like to write a loop that does the table for each variable. I should also point out that my data set has several missing observations and sometimes the observations that are missing are not the same for all my variables.
>
> What I would like to do:
>
> table(StoreData$CompanyID,
>        !is.na(StoreData$P2))
> table(StoreData$CompanyID,
>        !is.na(StoreData$P5))
>
> If I run the above code, I get:
>
>> table(StoreData$CompanyID,
> +         !is.na(StoreData$P2))
>
>    FALSE TRUE
>  2   940    0
>  3     0  323
>  4   288    0
>  5   306    0
>
>> table(StoreData$CompanyID,
> +         !is.na(StoreData$P5))
>
>    FALSE TRUE
>  2   940    0
>  3     0  323
>  4   288    0
>  5   306    0
>
>
> Here's the loop that I wrote, which does not work:
>
> angus <- c(2,5)
>
> for(i in angus) {
>  cut <- paste("StoreData$P",i, sep="")
>  table(StoreData$CompanyID, !is.na(cut))
>  }
>
> When I run the above, I get the following error message:
>
> Error in table(StoreData$CompanyID, !is.na(cut)) :
>  all arguments must have the same length
>> source(.trPaths[5], echo=TRUE, max.deparse.length=150)
>
> Any help is greatly appreciated!
> Stella
>
>
>
>
>        [[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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list