Hello R-users I have a situation like this x=c(1,3,2) y=data.frame("a"=1:3, "b"=4:6, "c"=7:9)*2 So we have> t(t(x))[,1] [1,] 1 [2,] 3 [3,] 2 And> ya b c 1 2 8 14 2 4 10 16 3 6 12 18 I would like to obtain a vector with number taken from the data.frame: x is needed as row index With c(1,3,2), in this case the ouput should be 2 16 12 I've tried a little bit with apply, but unsuccessfully. Thank you
> Da: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] > Per conto di Luca Braglia > Inviato: venerd? 11 settembre 2009 10.17 > A: r-help at r-project.org > Oggetto: [R] how to do this?> in this case the ouput should be > > 2 > 16 > 12 >Obviously this .... id.match = rep(0, nrow(y)) for (indice in 1:nrow(y)) { id.match[indice] <- y[indice, x[indice]] } id.match ... works, but it's not that good solution (especially for big data.frame) Thank you
Try this:> y[matrix(c(seq_along(x), x), ncol = 2)][1] 2 16 12 On Fri, Sep 11, 2009 at 4:17 PM, Luca Braglia <braglia at poleis.eu> wrote:> Hello R-users > > I have a situation like this > > x=c(1,3,2) > > y=data.frame("a"=1:3, "b"=4:6, "c"=7:9)*2 > > So we have > >> t(t(x)) > ? ? [,1] > [1,] ? ?1 > [2,] ? ?3 > [3,] ? ?2 > > And > >> y > ?a ?b ?c > 1 2 ?8 14 > 2 4 10 16 > 3 6 12 18 > > I would like to obtain a vector with number taken from the data.frame: x is needed as row index > > With c(1,3,2), in this case the ouput should be > > 2 > 16 > 12 > > I've tried a little bit with apply, but unsuccessfully. > > Thank you > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
Try this: y[cbind(seq(length(x)), x)] On Fri, Sep 11, 2009 at 5:17 AM, Luca Braglia <braglia@poleis.eu> wrote:> Hello R-users > > I have a situation like this > > x=c(1,3,2) > > y=data.frame("a"=1:3, "b"=4:6, "c"=7:9)*2 > > So we have > > > t(t(x)) > [,1] > [1,] 1 > [2,] 3 > [3,] 2 > > And > > > y > a b c > 1 2 8 14 > 2 4 10 16 > 3 6 12 18 > > I would like to obtain a vector with number taken from the data.frame: x is > needed as row index > > With c(1,3,2), in this case the ouput should be > > 2 > 16 > 12 > > I've tried a little bit with apply, but unsuccessfully. > > Thank you > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]