英文:
How to set row names for inner levels in a nested list?
问题
在以下嵌套列表中,我需要将行名称设置为resource
,行名称应从bodyPart
中获取。我希望将此应用于所有对象(例如,obj1,obj2)。
obj1 <- list(resource = list(bodyPart = c("leg", "arm", "knee"), side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", "LSM", "GHT")), cat = list(lab = c("aa", "bb", "cc")))
obj2 <- list(resource = list(bodyPart = c("leg", "arm", "knee"), side = c("LEFT", "LEFT", "LEFT"), device = c("GOM", "LSM", "YYY")))
x <- list(foo = c(fer = "wdb", obj1), bar = obj2)
我希望输出看起来像这样,例如对于obj2。
bodyPart | side | device | |
---|---|---|---|
leg | leg | LEFT | GOM |
arm | arm | LEFT | LSM |
knee | knee | LEFT | YYY |
感谢您的建议。
英文:
In the nested list below, I need to set row names to resource
and the row names should be taken from bodyPart
. I want this to be applied to all objects (e.g., obj1, obj2)
obj1 <- list(resource = list(bodyPart = c("leg", "arm", "knee"),side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", "LSM", "GHT")), cat = list(lab = c("aa", "bb", "cc")))
obj2 <- list(resource = list(bodyPart = c("leg", "arm", "knee"), side = c("LEFT", "LEFT", "LEFT"), device = c("GOM", "LSM", "YYY")))
x <- list(foo = c(fer = "wdb", obj1), bar = obj2)
I would like the output to look like this at resource level, for instance for obj2.
bodyPart | side | device | |
---|---|---|---|
leg | leg | LEFT | GOM |
arm | arm | LEFT | LSM |
knee | knee | LEFT | YYY |
I appreciate your edvice.
答案1
得分: 1
Alternatively we could use
obj2$resource %>% as.data.frame() %>% mutate(bodyPart2=bodyPart) %>%
column_to_rownames(var = 'bodyPart2')
output
bodyPart side device
leg leg LEFT GOM
arm arm LEFT LSM
knee knee LEFT YYY
<details>
<summary>英文:</summary>
Alternatively we could use
```r
obj2$resource %>% as.data.frame() %>% mutate(bodyPart2=bodyPart) %>%
column_to_rownames(var = 'bodyPart2')
# output
bodyPart side device
leg leg LEFT GOM
arm arm LEFT LSM
knee knee LEFT YYY
答案2
得分: 0
已编辑为双重lapply
:
lapply(x, function(y) {
lapply(y, function(z) {
if ("bodyPart" %in% names(z)) {
`rownames<-`(as.data.frame(z), z[["bodyPart"]])
} else z
})
})
# $foo
# $foo$fer
# [1] "wdb"
# $foo$resource
# bodyPart side device
# leg leg LEFT LLI
# arm arm RIGHT LSM
# knee knee LEFT GHT
# $foo$cat
# $foo$cat$lab
# [1] "aa" "bb" "cc"
# $bar
# $bar$resource
# bodyPart side device
# leg leg LEFT GOM
# arm arm LEFT LSM
# knee knee LEFT YYY
英文:
Edited to make it a double-lapply
:
lapply(x, function(y) {
lapply(y, function(z) {
if ("bodyPart" %in% names(z)) {
`rownames<-`(as.data.frame(z), z[["bodyPart"]])
} else z
)
)
# $foo
# $foo$fer
# [1] "wdb"
# $foo$resource
# bodyPart side device
# leg leg LEFT LLI
# arm arm RIGHT LSM
# knee knee LEFT GHT
# $foo$cat
# $foo$cat$lab
# [1] "aa" "bb" "cc"
# $bar
# $bar$resource
# bodyPart side device
# leg leg LEFT GOM
# arm arm LEFT LSM
# knee knee LEFT YYY
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论