Subsetting lists via logical index vectors

后端 未结 2 1544
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 17:36

I have a complex list and need to select a subset from it, based on the value of a boolean element (I need records with hidden value e

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 18:01

    The example data in the question is a list of length 3 which we shall call L. Each of its components is itself a list and one component of each of these sublists is hidden. We can extract the hidden components of the sublists into a logical vector called hidden. Using that logical vector we can subset the original list L giving a new list containing only those sublists with a hidden component of TRUE.

    hidden <- sapply(L, "[[", "hidden") # create logical vector hidden
    L[hidden]
    

    For the data provided we get a list with one component:

    > length(L[hidden])
    [1] 1
    

    and if we knew that there were only one component then L[hidden][[1]] or L[[which(hidden)]] would give that single component.

提交回复
热议问题