R:要列出的data.frame行

时间:2014-10-25 15:22:53

标签: r rmongodb

我有一个data.frame,现在我想将每一行转换为一个列,其中包含列名称和键,以及相应行的帧值。

f <- function(row) { mongo.bson.from.list(row to list) }
apply(df, 1, f)

数据框看起来像这样

> h
  id      stamp stmt1 stmt2 stmt3 stmt4 stmt5 stmt6 stmt7 stmt8
1  1 1398288482   "0"   "1"   "0"   "1"   "1"   "1"   "0"   "1"
2  2 1398288765   "1"   "0"   "0"   "0"   "1"   "1"   "0"   "0"
3  3 1398288804   "1"   "1"   "1"   "1"   "1"   "1"   "1"   "1"

我想要的是一种将数据帧的每一行转换为

的自动方式
list(id=1, stamp=1398288482, stmt1="0", stmt2="1", ...)

1 个答案:

答案 0 :(得分:1)

看看@ akrun建议的变化很有意思:

lapply(split(h, 1:nrow(h)), as.list)  # does deliver the requested object
lapply(split(h, 1:nrow(h)), list)     # a three element list with named atomic vectors
lapply(split(h, 1:nrow(h)), c)       # same as first
lapply(split(h, 1:nrow(h)), structure) #looks the same as first, but are actually data.frames

如果您想要“规范化”表单,reshape( ..., direction="long") - 方法可能会有用:

> reshape(h, varying=3:10, direction="long", sep="")
    id      stamp time stmt
1.1  1 1398288482    1    0
2.1  2 1398288765    1    1
3.1  3 1398288804    1    1
1.2  1 1398288482    2    1
2.2  2 1398288765    2    0
3.2  3 1398288804    2    1
1.3  1 1398288482    3    0
2.3  2 1398288765    3    0
3.3  3 1398288804    3    1
1.4  1 1398288482    4    1
2.4  2 1398288765    4    0
3.4  3 1398288804    4    1
1.5  1 1398288482    5    1
2.5  2 1398288765    5    1
3.5  3 1398288804    5    1
1.6  1 1398288482    6    1
2.6  2 1398288765    6    1
3.6  3 1398288804    6    1
1.7  1 1398288482    7    0
2.7  2 1398288765    7    0
3.7  3 1398288804    7    1
1.8  1 1398288482    8    1
2.8  2 1398288765    8    0
3.8  3 1398288804    8    1