[R] Matrix of indexes to extract sparse data in dataframe

Sergio Fonda sergio.fonda99 at gmail.com
Fri Jun 5 15:06:34 CEST 2015


I would like to avoid a "for loop" to get a vector of data taken from
rows of a data frame for specific columns.
An example is the following (I can't apply min to every row of df, this is
just an example):

c0=data.frame(a=c(3,-2,12,7,-23,17) , b=c(-1,-3,14,2,6,19))
c1=apply(c0,1,which.min)
> c1
[1] 2 2 1 2 1 1

I would like to get a result like the following call, but without
employing a "for loop":

d1=c(c0[1,c1[1]], c0[2,c1[2]], c0[3,c1[3]], c0[4,c1[4]], c0[5,c1[5]],
c0[6,c1[6]])
> d1
[1]  -1  -3  12   2 -23  17

Thanks a lot for any help!



More information about the R-help mailing list