[R] Looking for a more elegant solution than a loop

Fox, John jfox at mcmaster.ca
Tue Oct 27 02:47:10 CET 2015


Dear Erin,

How about

> x <- 6:9
> as.list(x)
[[1]]
[1] 6

[[2]]
[1] 7

[[3]]
[1] 8

[[4]]
[1] 9

Best,
 John

-----------------------------
John Fox, Professor
McMaster University
Hamilton, Ontario
Canada L8S 4M4
Web: socserv.mcmaster.ca/jfox



> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Erin
> Hodgess
> Sent: October 26, 2015 9:32 PM
> To: R help <r-help at stat.math.ethz.ch>
> Subject: [R] Looking for a more elegant solution than a loop
> 
> Hello!
> 
> The following (which is a toy example) works fine, but I wonder if there is a
> better or more elegant way than to do the loop:
> 
>  xz <- vector("list",length=4)
>  x <- 6:9
>  for(i in 1:4)xz[[i]] <- x[i]
>  xz
> [[1]]
> [1] 6
> 
> [[2]]
> [1] 7
> 
> [[3]]
> [1] 8
> 
> [[4]]
> [1] 9
> 
> This does exactly what I want, but the "for" loop seems out of place.
> Maybe not.
> 
> Thanks,
> Sincerely
> Erin
> 
> 
> --
> Erin Hodgess
> Associate Professor
> Department of Mathematical and Statistics University of Houston -
> Downtown
> mailto: erinm.hodgess at gmail.com
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



More information about the R-help mailing list