[R] For-loop,string variables, and the $-operator

Rui Barradas ruipbarradas at sapo.pt
Wed Nov 28 00:06:35 CET 2012


Hello,

It's bad to use the subset operator '$' because you don't have a column 
named 'j'. Use data[[j]]

Hope this helps,

Rui Barradas
Em 27-11-2012 21:22, Allan Schwade escreveu:
> Hi all,
>
> First time poster, so sorry if I commit some breech of posting etiquette.
>
> My problem is as follows. I have a data frame where each column represents
> a category and the individual data points in each category are binary
> responses (in this case they are actually 1's and 0's). What I want to
> extract are the counts for each category and put them in a vector. To do
> that I used the following:
>
> cats<-c("cat1","cat2", "cat3", ...)
> c()->counts
> for(j in cats){
>                      append(counts, sum(data$j)) -> counts
>                        }
>
> However, the 'counts' object only contains 0's after the script runs:
>
> counts
> [1] 0, 0, 0, ....
>
>   After replacing various elements in the script to isolate what the issue
> is, I've discovered the problem stems from  "data$j". Is there a reason
> using a variable with the subset operator is bad?
>
> Thanks,
> Allan
>
> 	[[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.




More information about the R-help mailing list