[R] Probably a good use for apply
Jim Lemon
jim at bitwrit.com.au
Thu May 31 11:35:55 CEST 2012
On 05/31/2012 10:50 AM, LCOG1 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"))
Hi Josh,
How about this?
test..
Apples Pears Beans
1 1 0 1
2 3 0 2
3 0 1 1
4 0 0 0
5 1 2 0
indices2names<-function(x,xnames) return(rep(xnames,x))
apply(as.matrix(test..),1,indices2names,names(test..))
[[1]]
[1] "Apples" "Beans"
[[2]]
[1] "Apples" "Apples" "Apples" "Beans" "Beans"
[[3]]
[1] "Pears" "Beans"
[[4]]
character(0)
[[5]]
[1] "Apples" "Pears" "Pears"
Jim
More information about the R-help
mailing list