Wednesday, 15 February 2012

Converting strange data.frame to matrix in R -



Converting strange data.frame to matrix in R -

i have next data.frame , convert matrix object after deleting each delimiter.

> info id col1 col2 col3 col4 col5 1 1 1,2,3,4 5,6,7,8 9,10,11,12 13,14,15,16 17,18,19,20 2 2 11,12,13,14 15,16,17,18 19,20,21,22 23,24,25,26 27,28,29,30 3 3 21,22,23,24 25,26,27,28 29,30,31,32 33,34,35,36 37,38,39,40 4 4 31,32,33,34 35,36,37,38 39,40,41,42 43,44,45,46 47,48,49,50 5 5 41,42,43,44 45,46,47,48 49,50,51,52 53,54,55,56 57,58,59,60 6 6 51,52,53,54 55,56,57,58 59,60,61,62 63,64,65,66 67,68,69,70 7 7 61,62,63,64 65,66,67,68 69,70,71,72 73,74,75,76 77,78,79,80 8 8 71,72,73,74 75,76,77,78 79,80,81,82 83,84,85,86 87,88,89,90 9 9 81,82,83,84 85,86,87,88 89,90,91,92 93,94,95,96 97,98,99,100

===>

> data.new [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] 1 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2 2 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 3 3 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4 4 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 5 5 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 6 6 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7 7 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 8 8 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 9 9 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

to this, functions of apply() should apply?

thanks in advance sean

you don't need apply @ all. can re-read data. seek of these 3 possibilities.

in base of operations r, (1) paste columns row read text read.csv

dc <- do.call(paste, c(data, list(sep = ","))) unname(as.matrix(read.csv(text = dc, header = false)))

or, (2) using scan directly

matrix(scan(text = dc, = integer(), sep = ","), length(dc), byrow = true)

or, (3) utilize csplit splitstackshape

library(splitstackshape) unname(as.matrix(csplit(data, 2:6)))

r

No comments:

Post a Comment