簡體   English   中英

應用於無法在R中使用的列表列表

[英]lapply on a list of list not working in R

我有

typeof(A)
>"list"
typeof(A[1])
>"list"
typeof(A[[1]])
>"double"

當我跑步時

A=lapply(A,unlist)
typeof(A[1])
>"list"

結果似乎是相同的。 但是如果我跑步

B=unlist(A[1])
typeof(B)
"double"

請幫助我了解這種行為。 為什么兩者之間有區別? lapply是否不應該將函數應用於列表的每個元素? 比A [i]應該像B?

lapply實際上返回一個列表作為其輸出。 它將一個函數應用於多個元素,並將每個輸出作為列表的一個元素返回。

值得A[[1]]是,類型為double的A[[1]]實際上會告訴您您有一個double列表。 [[ ]]引用列表的元素, []引用向量的元素。 因此,通過要求A[1]您將獲得第一個元素作為列表,通過要求A[[1]]您將使第一個元素被除名。

我懷疑您想要的只是unlist(A) 這會將A的每個元素作為單個向量中的一個元素返回。 在您的情況下,A是雙打列表。 希望這就是您想要的。

舉個例子

test = list(list(5), list(3), list(1))
> test #Notice this is a list of lists, each containing one element
[[1]]
[[1]][[1]]
[1] 5


[[2]]
[[2]][[1]]
[1] 3


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

> test[2] #Notice this has exported the second element as a new list with one element
[[1]]
[[1]][[1]]
[1] 3

> test[[2]] #Notice this has exported the second element not as a list, so now we have one listed instead of two nested lists.
[[1]]
[1] 3

lapply(test, unlist) #This returns a list of element rather than a list of lists
[[1]]
[1] 5

[[2]]
[1] 3

[[3]]
[1] 1

unlist(lapply(test, unlist)) #This returns a vector of elements by unlisting the list of elements we created in the previous step
[1] 5 3 1

我希望這可以清除某些行為:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM