R 拆分列表的分层列表

K.I*_*.I. 1 r list

我有一个清单。我想把这个列表分成两个列表。最好用例子来解释。这是一个例子。

列表由 3 个列表组成。每个列表元素都是 2 个 data.frame 的列表。(人、车)

df1 = data.frame(id = 1, name = "John")
df2 = data.frame(id = 1, car = "Opel")

list1 = list(person = df1, car = df2)
list2 = list(person = df1, car = df2)
list3 = list(person = df1, car = df2)

listMain = list(list1,list2,list3)
Run Code Online (Sandbox Code Playgroud)

的输出str(listMain):

List of 3
 $ :List of 2
  ..$ person:'data.frame':  1 obs. of  2 variables:
  .. ..$ id  : num 1
  .. ..$ name: Factor w/ 1 level "John": 1
  ..$ car   :'data.frame':  1 obs. of  2 variables:
  .. ..$ id : num 1
  .. ..$ car: Factor w/ 1 level "Opel": 1
 $ :List of 2
  ..$ person:'data.frame':  1 obs. of  2 variables:
  .. ..$ id  : num 1
  .. ..$ name: Factor w/ 1 level "John": 1
  ..$ car   :'data.frame':  1 obs. of  2 variables:
  .. ..$ id : num 1
  .. ..$ car: Factor w/ 1 level "Opel": 1
 $ :List of 2
  ..$ person:'data.frame':  1 obs. of  2 variables:
  .. ..$ id  : num 1
  .. ..$ name: Factor w/ 1 level "John": 1
  ..$ car   :'data.frame':  1 obs. of  2 variables:
  .. ..$ id : num 1
  .. ..$ car: Factor w/ 1 level "Opel": 1
Run Code Online (Sandbox Code Playgroud)

我想把这个列表分成两个列表。第一个应该是 personList,第二个是 carList。像这样。

> listPerson <- list(df1,df2,df3)
> str(listPerson)
List of 3
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id  : num 1
  ..$ name: Factor w/ 1 level "John": 1
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id  : num 1
  ..$ name: Factor w/ 1 level "John": 1
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id  : num 1
  ..$ name: Factor w/ 1 level "John": 1
> listCars <- list(df4,df5,df6)
> str(listCars)
List of 3
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id : num 1
  ..$ car: Factor w/ 1 level "Opel": 1
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id : num 1
  ..$ car: Factor w/ 1 level "Opel": 1
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ id : num 1
  ..$ car: Factor w/ 1 level "Opel": 1
Run Code Online (Sandbox Code Playgroud)

怎么做?提前致谢。

Hei*_*erg 5

您可以使用lapply遍历每个元素listMain并提取第一个(第二个)元素。我认为这里的关键点是[[像lapply.

listPerson <- lapply(listMain, `[[`, 1)
listCar <- lapply(listMain, `[[`, 2)
Run Code Online (Sandbox Code Playgroud)

正如 @Frank 在评论中建议的那样,您也可以按名称进行子集化。关键点仍然是您可以[[像常规函数一样使用。

listPerson <- lapply(listMain, `[[`, "person")
Run Code Online (Sandbox Code Playgroud)

要阅读此函数的文档,请输入?`[[`。