【问题标题】:R: data.frame rows to listR:要列出的 data.frame 行
【发布时间】:2014-10-25 15:22:52
【问题描述】:

我有一个 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", ...)

【问题讨论】:

  • 为什么要投反对票?请解释一下?
  • 我还不是反对者之一,但您确实需要包含一个数据框示例和一个示例,说明该示例的正确输出应该是什么。对于 R 对象的准确描述,没有术语“键”。列名已经可以用于索引数据框列。也许您希望每一行都作为一个单独的命名向量?如果您希望使用外部包,您应该包含将加载它的代码。
  • @Jeremy Knees 试试lapply(split(h, 1:nrow(h)), as.list)

标签: r rmongodb


【解决方案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")-approach 可能会很有用:

> 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

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多