R: data.frame rows to list

倾然丶 夕夏残阳落幕 提交于 2019-12-25 17:17:29

问题


I'm having a data.frame and now I want to convert each row to a list with as keys the column names and values the frame values of that respective row.

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

the data frame looks like this

> 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"

what I want is an automated way to transform each row of the dataframe into

list(id=1, stamp=1398288482, stmt1="0", stmt2="1", ...)

回答1:


It's interesting to look at variations on @akrun's suggestion:

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

If you wanted a "normalized" form, the reshape( ..., direction="long")-approach might be useful:

> 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


来源:https://stackoverflow.com/questions/26563975/r-data-frame-rows-to-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!