[R] Indexing Elements of a Dataframe
John Fox
jfox at mcmaster.ca
Tue May 28 23:53:19 CEST 2002
Dear Wolfgang,
I'm not sure exactly what you want to do, or why the result needs to be a
data frame, but what about something like the following?
> rows <- c(10, 20, 30)
> cols <- c(200, 400, 600)
> df <- as.data.frame(outer(rows, cols, function(r, c) r + c))
> row.names(df) <- letters[1:3]
> names(df) <- LETTERS[1:3]
> df
A B C
a 210 410 610
b 220 420 620
c 230 430 630
Or perhaps you want the elements of rows and cols as row and column names:
> row.names(df) <- rows
> names(df) <- cols
> df
200 400 600
10 210 410 610
20 220 420 620
30 230 430 630
Of course, you'd replace the function argument to outer with an appropriate
function.
I hope that this helps,
John
At 01:40 PM 5/28/2002 -0500, Wolfgang Viechtbauer wrote:
>Let's say that I have the following code:
>
>for (i in c(10, 20, 30)) {
> for (j in c(200, 400, 600)) {
> ...
> ...
> x <- "something"
> * (code here)
> }
>}
>
>* Now, x is some result that I want to put into a results "matrix" that
>looks like this:
>
> 200 400 600
>10
>20
>30
>
>I came up with an ad-hoc solution adding some counters (called "ro" and
>"co") and using a matrix for the results, which I could index with those
>counters (results[ro,co] <- x) and then converting that matrix into a
>dataframe and changing the row and column names. That seems a little too
>convoluted.
>
>I tried to come up with a "neater" solution, trying to create a
>dataframe that looks like the one above and then indexing the fields in
>the dataframe by results$i[j] but I couldn't get it to work. Is there a
>way of doing this or maybe a better solution?
-----------------------------------------------------
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
-----------------------------------------------------
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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