convertingnumericarraysintolistandsaviginCSVinR

I am trying to store two numerical arrays in an unusal form, e.g. c('[1;2;3]','[4;5;6]','[24;25;26]')

I need them in a CSV in single cells, like here

So far I tried this:

DF
ID time Y
1  3    23
1  4    24
1  5    20 
2  2    12
2  8    15
3  2    19
3  3    23
3  5    21
3  6    32

timeList = list()
yList = list()
for (i in 1:3) {
  timeList[i] = DF$time
  yList[i] = DF$Y   
}

longTimeList = list(timeList)
longYList = list(yList)

DF <- data.frame(ID = c(1,2,3),
             P1 = longTimeList,
             P2 = longYList)

so the example DF woul read

 newDF <- data.frame(ID = c(1,2,3),
                 P1 = c('[3;4;5]','[2;8]','[2;3;5;6]'),
                 P2 = c('[23,24,20]','[12;15]','[19;23;21;32]'))

which should be stored in a CSV file to give something like that shown above.

回答

我相信aggregate可以帮助你

> aggregate(. ~ ID, DF, function(x) sprintf("[%s]", paste0(x, collapse = ";")))
  ID      time             Y
1  1   [3;4;5]    [23;24;20]
2  2     [2;8]       [12;15]
3  3 [2;3;5;6] [19;23;21;32]


以上是convertingnumericarraysintolistandsaviginCSVinR的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>