r - How to group a vector into a list of vectors? -


i have data looks (fake data example's sake):

dressid        color  6              yellow  9              red 10             green  10             purple  10             yellow  12             purple  12             red  

where color factor vector. not guaranteed possible levels of factor appear in data (e.g. color "blue" 1 of levels).

i need list of vectors groups available colors of each dress:

[[1]] yellow    [[2]]  red      [[3]]  green purple yellow   [[4]]  purple red  

preserving ids of dresses nice (e.g. dataframe list second column , ids first), not necessary.

i wrote loop goes through dataframe row row, , while next id same, adds color vector. (i sure data sorted id). when id in first column changes, adds vector list:

result <- null  while(blah blah)  {     code creates vector called "colors"      result[[dresscounter]] <- colors      dresscounter <- dresscounter + 1 } 

after wrestling getting necessary counting variables correct, found out dismay doesn't work. first time, colors

[1] yellow levels: green yellow purple red blue 

and gets coerced integer, result becomes 2.

in second loop repetition, colors contains red, , result becomes simple integer vector, [1] 2 4.

in third repetition, colors vector now,

[1] green  purple yellow levels: green yellow purple red blue  

and

result[[3]] <- colors 

error in result[[3]] <- colors :
more elements supplied there replace

what doing wrong? there way initialize result doesn't converted numeric vector, becomes list of vectors?

also, there way whole thing "roll own"?

split.data.frame way organize this; extract color component.

d <- data.frame(dressid=c(6,9,10,10,10,12,12),                color=factor(c("yellow","red","green",                               "purple","yellow",                               "purple","red"),                  levels=c("red","orange","yellow",                           "green","blue","purple"))) 

i think version want this:

ss <- split.data.frame(d,d$dressid) 

you can more list requested extracting color component:

lapply(ss,"[[","color") 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -