[R] Is there a sexy way ...?

Kimmo Elo k|mmo@e|o @end|ng |rom ue|@||
Fri Sep 27 08:01:20 CEST 2024


Dear Rolf, dear all,

this was an inspiring challenge :-) This seems to do the task...

--- snip ---

x <- list(`1` = c(7, 13, 1, 4, 10),
           `2` = c(2, 5,  14, 8, 11),
           `3` = c(6, 9, 15, 12, 3))

f <- factor(rep(1:3,5))

v <- as.vector(unlist(x)[ paste(rep(levels(f), length(x[[1]])), 
rep(1:length(x[[1]]), each=length(levels(f))), sep="") ])

v

--- snip ---

I leave it to you, whether this is an elegant solution or not ;-)

Cheers,

Kimmo

Rolf Turner kirjoitti 27.9.2024 klo 6.55:
> 
> I have (toy example):
> 
> x <- list(`1` = c(7, 13, 1, 4, 10),
>            `2` = c(2, 5,  14, 8, 11),
>            `3` = c(6, 9, 15, 12, 3))
> and
> 
> f <- factor(rep(1:3,5))
> 
> I want to create a vector v of length 15 such that the entries of v,
> corresponding to level l of f are the entries of x[[l]].  I.e. I want
> v to equal
> 
>      c(7, 2, 6, 13, 5, 9, 1, 14, 15, 4, 8, 12, 10, 11, 3)
> 
> I can create v "easily enough", using say, a for-loop.  It seems to me,
> though, that there should be sexier (single command) way of achieving
> the desired result.  However I cannot devise one.
> 
> Can anyone point me in the right direction?  Thanks.
> 
> cheers,
> 
> Rolf Turner
> 

-- 
Kimmo Elo
Senior Lecturer | Adjunct professor, Dr.
========================================================
University of Eastern Finland
Department of Geographical and Historical Studies
P.O. Box 111
FIN-80101 Joensuu
Finland
E-mail: kimmo.elo using uef.fi
ResearchGate: www.researchgate.net/profile/Kimmo_Elo
LAWPOL Consortium (PI): https://lawpol.fi/en
========================================================


More information about the R-help mailing list