简体   繁体   English

将数据框中的行转换为r中的列表列表

[英]convert row in data frame to list of lists in r

I have a data frame consisting of records like the following. 我有一个包含如下记录的数据框。 A typical row of the data frame, df[1,] looks as follows 数据帧的典型行df [1]如下所示

84745,"F",70,7,"Single",2,"N",4,9,1,1,3,4,4,"2 day","<120 and <80",0,8,0,1,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1

I want to convert it into a variable like myvar below which is of the following type 我想将其转换为以下类型的变量,例如myvar,其类型如下

myvar = list( list(84745,"F",70,7,"Single",2,"N",4,9,1,1,3,4,4,"2 day","<120 and <80",0,8,0,1,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1))

I have tried doing the following, but it doesn't work to convert it to a list of lists. 我尝试执行以下操作,但是将其转换为列表列表无效。

myvar <- as.list(as.list(as.data.frame(t(df[1,]))))

How can I do that? 我怎样才能做到这一点?

EDIT : I have tried myvar = list(unclass(df[14,])). 编辑:我已经尝试过myvar = list(unclass(df [14,]))。 It however fails the call since the formatting of the output myvar is slightly different. 但是,由于输出myvar的格式略有不同,因此无法调用。

Format of the original line of code 原始代码行的格式

[[1]]
[[1]][[1]]
[1] 21408

[[1]][[2]]
[1] "M"

[[1]][[3]]
[1] 69

[[1]][[4]]
[1] 3

[[1]][[5]]
[1] "Widowed"

Format of myvar = list(unclass(df[14,])) myvar = list(unclass(df [14,]))的格式

[[1]]
[[1]]$ID
[1] "21408"

[[1]]$GenderCD
[1] "M"

[[1]]$Age
[1] "69"

[[1]]$LOS
[1] "3"

[[1]]$MaritalStatus
[1] "Widowed"

Try this: 尝试这个:

 myvar <- list( unclass( df[1,] )

Explanation: df[1,] is actually still a list but with a "data.frame" class attribute. 说明:df [1,]实际上仍然是一个列表,但是具有“ data.frame”类属性。 If you remove its class it's now just an ordinary list. 如果删除其类,则现在只是普通列表。 When you conducted the t(df[1,] -operation you forced that row to become a column vector which in a dataframe needed to all be the came class so coercion occurred. 当您执行t(df[1,]操作时,您迫使该行成为列向量,在数据帧中所有这些列都必须是Come类,因此会发生强制转换。

If the goal is a row-by-row solution then do this: 如果目标是逐行解决方案,请执行以下操作:

 myvar <- list()
 for (i in seq(nrow(df)) ) { myvar[[i]]  <-  unclass( df[i,] )}

If it also needs to be unnamed which I rather doubt but I suppose it's possible then: 如果还需要取消命名,我相当怀疑,但是我想这是可能的:

 myvar <- list()
 for (i in seq(nrow(df)) ) { myvar[[i]]  <-  unname( unclass( df[i,] )) }

I tested the unname strategy with: 我用以下方法测试了unname策略:

> unname(unclass( data.frame(a=345,b="tyt")[1,]))
[[1]]
[1] 345

[[2]]
[1] tyt
Levels: tyt

attr(,"row.names")
[1] 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM