【发布时间】:2019-12-21 23:49:15
【问题描述】:
这是一个微不足道的问题,但我很难过。如何根据数据框的长度过滤数据框列表?该列表是嵌套的——这意味着有不同长度的数据帧列表的列表。这是一个例子。我想过滤或子集列表以仅包含长度为 n 的对象,例如 3。
这是一个例子和我目前的方法。
library(tidyverse)
# list of list with arbitrary lengths
star.wars_ls <- list(starwars[1:5],
list(starwars[1:8], starwars[4:6]),
starwars[1:2],
list(starwars[1:7], starwars[2:6]),
starwars[1:3])
# I want to filter the list by dataframes that are 3 variables long (i.e. length(df == 3).
# Here is my attempt, I'm stuck at how to obtain
# the number of varibles in each dataframe and then filter by it.
map(star.wars_ls, function(x){
map(x, function(x){ ## Incorrectly returns 20 for all
length(y)
})
})
【问题讨论】:
-
你想对嵌套做什么?松散?忽视?分层应用过滤器?
-
我想在适用时保留嵌套。所以我想最好分层应用过滤器。
-
我现在将对其进行编辑。谢谢。
-
嗯,我认为“递归过滤”可能比“分层过滤”更好。 This looks promising
-
我认为您还需要编辑以 (a) 定义
n和 (b) 定义y。很高兴看到预期的结果。比如,如果n是3,你想要list(NULL, list(NULL, starwars[4:6]), list(NULL, NULL), starwars[1:3])吗?还是别的什么?