in R, extract part of object from list

前端 未结 1 1449
温柔的废话
温柔的废话 2020-12-05 11:08

I\'m just learning R and having a hard time wrapping my head around how to extract elements from objects in a list. I\'ve parsed a json file into R giving me list object.

相关标签:
1条回答
  • 2020-12-05 11:25

    sapply is going to apply some function to every element in your list. In your case, you want to access each element in a (nested) list. sapply is certainly capable of this. For instance, if you want to access the first child of every element in your list:

    sapply(listJson, "[[", 1)
    

    Or if you wanted to access the item named "favorited", you could use:

    sapply(listJson, "[[", "favorited")
    

    Note that the [ operator will take a subset of the list you're working with. So when you access myList[1], you still have a list, it's just of length 1. However, if you reference myList[[1]], you'll get the contents of the first space in your list (which may or may not be another list). Thus, you'll use the [[ operator in sapply, because you want to get down to the contents of the list.

    0 讨论(0)
提交回复
热议问题