[英]Defining nested list into a vector with default R packages
myList <- rep(0, 5)
myList <- list('Aa'= c("1","12"), 'Ba'= c("123","321"), 'Ca'= c("444"))
for (x in names(myList)) {
for (j in myList[x]) {
sample <- c(unlist(myList[j]))
} }
sample
在嵌套列表中,想要將此列表轉換為帶有
“為了”
環形
如果不定義 function,我無法弄清楚如何提取這些值。
sample <- c(unlist(myList[x])
執行“取消列出”僅使用其他代碼即可
> sample
NULL
但我想要所有,而這個不是那樣工作的。 有沒有基礎版? 無需快速或簡單。 僅帶有基本的 R 分發包,帶有
“不列出”的替代品
如果有可能。
我需要類似的東西
Aa1 Aa2 Ba1 Ba2 Ca1 "1" "12" "123" "444"
我想我不需要
我的列表 <- 代表(0, 5)
我可能不太明白你的問題,但不
sample <- unlist(myList)
# Aa1 Aa2 Ba1 Ba2 Ca
# "1" "12" "123" "321" "444"
或者
sample <- structure(unlist(myList))
# Aa1 Aa2 Ba1 Ba2 Ca
# "1" "12" "123" "321" "444"
達到你想要的?
如果我理解你的正確,你想在基礎unlist
中取消列出而不列出。 你可以這樣做:
res <- NULL
for (i in seq(names(myList))) {
nm <- names(myList)[i]
l <- myList[[nm]]
res<- c(res, setNames(l, paste0(nm, seq(l))))
}
res
# Aa1 Aa2 Ba1 Ba2 Ca1
# "1" "12" "123" "321" "444"
查看:
unlist(myList)
# Aa1 Aa2 Ba1 Ba2 Ca
# "1" "12" "123" "321" "444"
我也不得不承認不太了解您要達到的目標,但是如果您想要unlist()
的結果而不明確使用 function 您可以嘗試rapply()
- 盡管默認情況下unlist()
正在使用兜帽:
rapply(myList, f = function(x) x)
Aa1 Aa2 Ba1 Ba2 Ca
"1" "12" "123" "321" "444"
不太確定為什么要避免unlist
,但這是flatten_chr
的替代方案。
len <- lengths(myList)
setNames(purrr::flatten_chr(myList),paste0(rep(names(myList),len),sequence(len)))
# Aa1 Aa2 Ba1 Ba2 Ca1
# "1" "12" "123" "321" "444"
如果您可以稍微調整名稱,您也可以使用make.unique
:
setNames(purrr::flatten_chr(myList),make.unique(rep(names(myList), len),sep = ""))
# Aa Aa1 Ba Ba1 Ca
# "1" "12" "123" "321" "444"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.