tags:

views:

49

answers:

2

I have a data.frame x in R for which dim(x) = (m,n) and a vector y of numbers of length m and with values between 1 and n. In other words, y has an entry for each row in x and each value is a valid column number in x. I would like to extract a "jagged" column of numbers from x using the column numbers in y. For example, if

y <- c(2,4,1,6,5) 

then I would like to get a vector of numbers equal to

c(x[1,2],x[2,4],x[3,1],x[4,6],x[5,5])

What is the most efficient way to do this?

Thanks.

A: 

If I understood you right, you want values from the diagonal of the data frame you get from scrambling up the columns? Or something like that?

Iff x[,y] will always be square, then this should work:

diag.index <- diag(nrow = length(y)) == 1
x[ ,y][diag.index]
JoFrhwld
+4  A: 
> x <- matrix(rnorm(5 * 6), nrow = 5)
> x
            [,1]       [,2]       [,3]       [,4]       [,5]       [,6]
[1,] -0.8781820  0.4874737  0.5161918  0.5905719  0.1346253 -0.8108332
[2,]  1.2811044  0.2700776 -0.5694690 -1.2984173 -0.3491372  0.2315443
[3,]  1.1113906 -1.2589781  1.0206620  0.3396931 -0.7466635 -0.4369746
[4,]  0.2494311 -0.9985038 -0.7322118  0.3400631  1.0992965 -1.2063930
[5,]  0.5162947 -0.1346913  0.6835899  2.1042772 -1.5342266 -1.0558785
> y <- c(2,4,1,6,5)
> x[cbind(seq(y), y)]
[1]  0.4874737 -1.2984173  1.1113906 -1.2063930 -1.5342266
Jonathan Chang
Great... simple and does the job! =)
aL3xa
Thanks Jonathan. This is what I was looking for.
Abiel