r - 从嵌套列表创建数据框
问题描述
从嵌套列表创建数据框的最佳方法是什么。
#installing package
installed.packages("qdap")
#loading qdap package
library("qdap")
# Finding synonyms from the below function which gives a list.
data <- synonyms("power")
# Converting list to dataframe
plyr::ldply(data, cbind)
t(plyr::ldply(data, rbind))
最后,我想创建多个数据框。从以下输出:
synonyms(c("taste","company","power"))
使用 dput() 的列表输出看起来很相似
structure(list(power.def_1 = c("ability", "capability", "capacity",
"competence", "competency", "faculty", "potential"), power.def_2 = c("brawn",
"energy", "force", "forcefulness", "intensity", "might", "muscle",
"potency", "strength", "vigour", "weight"), power.def_3 = c("ascendancy",
"authority", "bottom", "command", "control", "dominance", "domination",
"dominion", "influence", "mastery", "rule", "sovereignty", "supremacy",
"sway"), power.def_4 = c("authority", "authorization", "licence",
"prerogative", "privilege", "right", "warrant")), .Names = c("power.def_1",
"power.def_2", "power.def_3", "power.def_4"))
解决方案
它会这样工作吗?
lapply(l, function(li)
data.frame(lapply(li,'length<-',max(lengths(li)))))
# [[1]]
# power.def_1 power.def_2 power.def_3 power.def_4
# 1 ability brawn ascendancy authority
# 2 capability energy authority authorization
# 3 capacity force bottom licence
# 4 competence forcefulness command prerogative
# 5 competency intensity control privilege
# 6 faculty might dominance right
# 7 potential muscle domination warrant
# 8 <NA> potency dominion <NA>
# 9 <NA> strength influence <NA>
# 10 <NA> vigour mastery <NA>
# 11 <NA> weight rule <NA>
# 12 <NA> <NA> sovereignty <NA>
# 13 <NA> <NA> supremacy <NA>
# 14 <NA> <NA> sway <NA>
...
使用更紧凑purrr
:
library(purrr)
map(l,~map_dfc(.,`length<-`,max(lengths(.))))
数据
l1 <- structure(list(power.def_1 = c("ability", "capability", "capacity",
"competence", "competency", "faculty", "potential"), power.def_2 = c("brawn",
"energy", "force", "forcefulness", "intensity", "might", "muscle",
"potency", "strength", "vigour", "weight"), power.def_3 = c("ascendancy",
"authority", "bottom", "command", "control", "dominance", "domination",
"dominion", "influence", "mastery", "rule", "sovereignty", "supremacy",
"sway"), power.def_4 = c("authority", "authorization", "licence",
"prerogative", "privilege", "right", "warrant")), .Names = c("power.def_1",
"power.def_2", "power.def_3", "power.def_4"))
l <- list(l1,l1)
推荐阅读
- php - 如何验证 CF7 文本字段中的邮政编码
- javascript - 当滚动回到顶部并删除类时跳跃动画元素
- android - 如何在适配器中调用 Activity 方法
- javascript - 如何在 Firefox 上触发请求访问 HTML5 画布数据的权限,而无需“通过用户交互”?(权限 API 中没有画布?)
- slurm - Slurm 工作负载管理器的作业提交问题
- flutter - Flutter 安全存储无法读取存在的密钥
- c - 无法理解循环是如何在这里运行的
- java - 无法使用 TOMCAT 9.0、Java、Hibernate、Eclipse 加载网页
- find - 文件名匹配的正则表达式
- django - 修改 auth_views.LogInView 中的字段标签