2

I have the array:

>cent
       b    e          r    f
A19 60.46   0.77    -0.12   1
A15 16.50   0.53    0.08    2
A17 2.66    0.51    0.20    3
A11 36.66   0.40    -0.25   4
A12 38.96   0.91    0.23    1
A05 0.00    0.29    0.01    2
A09 3.40    0.35    0.03    3
A04 0.00    0.25    -0.03   4

Could some one please say me how to split this array into 4 separate arrays where the last column «f» is the flag? In result I would like to see:

>cent1
       b    e          r    f
A19 60.46   0.77    -0.12   1
A12 38.96   0.91    0.23    1
>cent2
       b    e          r    f
A15 16.50   0.53    0.08    2
A05 0.00    0.29    0.01    2
….

Should I use the for-loop and check flag "f" or exist a build-in function? Thanks.

Nick
  • 1,086
  • 7
  • 21
  • If it's really an array, and not a data frame, then try [this one](http://stackoverflow.com/questions/30122693/named-arrays-dataframes-and-matrices) – Rich Scriven Jan 16 '16 at 17:58

1 Answers1

1

We can use split to create a list of data.frames.

 lst <- split(cent, cent$f)

NOTE: Here I assumed that the 'cent' is a data.frame. If it is a matrix

 lst <- split(as.data.frame(cent), cent[,"f"])

Usually, it is enough to do most of the analysis. But, if we need to create multiple objects in the global environment, we can use list2env (not recommended)

 list2env(lst, paste0("cent", seq_along(lst)), envir= .GlobalEnv)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thanks you for reply. The function split() is work. Now I have the list lst. How can I address to elements in the list lst[1] that are of the same type, say $b? – Nick Jan 17 '16 at 05:24
  • I have tried lst[1]$b, lst['1'], lst[1]$'1'. But I need to extract first column only. – Nick Jan 17 '16 at 08:19
  • @Nick If you need the first column `lst[[1]][1]` (if the dataset is data.frame) , if is is matrix `lst[[1]][,1]` – akrun Jan 17 '16 at 09:29