[R] easy question

John Fox jfox at mcmaster.ca
Tue Apr 29 13:27:23 CEST 2003


Dear Fabrizio

At 12:07 PM 4/29/2003 +0200, De Amicis Fabrizio (G.I.T.) wrote:
>Dear R.List,
>I am starting to use R. I have an easy question. In a dataset of 15
>variables, I am not able run correctly the index i of the do loop.
>Do you have any suggestion?
>
>NC <- function(x)
>
>     for (i in 1:15) {
>     print(dim(table(dt[,"Vi"])))
>
>}
>

The short answer is that you need to paste the number in i to "V" in order 
to create a proper column index. I assume that the columns of dt are named 
"V1", ..., "V15":

     print(dim(table(dt[,paste("V",i,sep="")])))

Alternatively, you could use something like

     for (i in paste("V",1:15,sep="")) print(dim(table(dt[,i])))

or even more simply, just index the columns by number

     for (i in 1:15) print(dim(table(x[,i])))

Some other points, however:

(1) The argument to your function is x, but you're indexing a variable 
called dt.

(2) A simpler approach to counting the unique elements in each column is

         apply(dt, 2, function(x) length(unique(x)))

(3) Since this apparently applies to a particular matrix or data frame, why 
write a function to perform the operation?

I hope that this helps,
  John

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox



More information about the R-help mailing list