[R] Probably a good use for apply
jim holtman
jholtman at gmail.com
Thu May 31 05:18:00 CEST 2012
try this:
> test.. <- data.frame(Apples = c(1,3,0,0,1), Pears = c(0,0,1,0,2), Beans =
+ c(1,2,1,0,0))
>
> lapply(seq(nrow(test..)), function(.row){
+ do.call(c, sapply(names(test..), function(.col){
+ rep(.col, test..[[.col]][.row])
+ }))
+ })
[[1]]
Apples Beans
"Apples" "Beans"
[[2]]
Apples1 Apples2 Apples3 Beans1 Beans2
"Apples" "Apples" "Apples" "Beans" "Beans"
[[3]]
Pears Beans
"Pears" "Beans"
[[4]]
character(0)
[[5]]
Apples Pears1 Pears2
"Apples" "Pears" "Pears"
On Wed, May 30, 2012 at 8:50 PM, LCOG1 <jroll at lcog.org> wrote:
> Hi all,
> I Have a data frame test.. that I would like to convert into a list below
> test_ but am unsure how to efficiently do this. I can do it in a for loop
> but my data set is huge and it takes forever. Wondering how I can do this
> more efficiently. So again how to I go from test.. to test_ below?
> #Data frame
> test.. <- data.frame(Apples = c(1,3,0,0,1), Pears = c(0,0,1,0,2), Beans =
> c(1,2,1,0,0))
>
> #list - my desired outcome
> test_ <- list("1" = c("Apples","Beans"),
> "2" = c("Apples","Apples","Apples","Beans","Beans"),
> "3" = c("Pears","Beans"),
> "4" = c(NULL),
> "5" = c("Apples","Pears","Pears"))
>
> Thanks
>
> Josh
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Probably-a-good-use-for-apply-tp4631883.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
More information about the R-help
mailing list