[R] accessing information in data.frame

Duncan Murdoch murdoch at stats.uwo.ca
Tue Nov 27 15:48:03 CET 2001

On Tue, 27 Nov 2001 14:32:27 +0100, you wrote in message
<3C0395EB.4E95CDA6 at epost.de>:

>After reading a data.frame using, such as a <- read.spss("data.sav")
>I want to give the column index 'i', or a[i] to a function, which after
>some calculation, should print out the results to the standard output.
>I am struggling how to access the data itself, as e.g. sum(a[i]) does
>not work in this context. In addition I need to know the name of the
>variable within the function in order to generate a meaningful output,
>and  have not found any way to obtain the name of the variable.

Data frames are lists that act a lot like matrices.  To get at column
i, use a[,i]  (i.e. all rows of column i, in matrix notation) or
a[[i]] (i.e. list element i).

If you use a[i] you get a data frame that consists only of column i,
which is probably not what you want to work with.  You want to extract
the column into a vector. 

I recommend always using the matrix notation when you want numerical
columns.  Only use list notation when you are extracting a named
column, i.e. use a$somecol rather than a[,'somecol'].

To get the name of column i, use names(a)[i].

Duncan Murdoch
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list