[英]How can I remove elements by columns number from a list?
如果元素數量少於3,我想刪除列表中的元素。
為此,我嘗試:
#Create a list
my_list <- list(a = c(3,5,6), b = c(3,1,0), c = 4, d = NA)
my_list
$a
[1] 3 5 6
$b
[1] 3 1 0
$c
[1] 4
$d
[1] NA
# Thant I create a function for remove the elements by my condition:
delete.F <- function(x.list){
x.list[unlist(lapply(x.list, function(x) ncol(x)) < 3)]}
delete.F(my_list)
我有作為輸出:
Error in unlist(lapply(x.list, function(x) ncol(x)) < 3) :
(list) object cannot be coerced to type 'double'
有什么想法嗎?
一種選擇是創建具有lengths
的邏輯表達式,並將其用於子集list
my_list[lengths(my_list) >=3]
#$a
#[1] 3 5 6
#$b
#[1] 3 1 0
請注意,在示例中,它是vector
的list
,而不是data.frame
的list
。 ncol/nrow
是當存在dim
屬性時- matrix
為此檢查TRUE, data.frame
也是data.frame
如果我們想以某種方式使用lapply
(基於某些約束),請創建具有length
的邏輯
unlist(lapply(my_list, function(x) if(length(x) >=3 ) x))
如果我們需要創建索引lapply
,使用length
(但它是慢lengths
)
my_list[unlist(lapply(my_list, length)) >= 3]
這里還有其他一些選擇。 在基本R中使用Filter
Filter(function(x) length(x) >=3, my_list)
#$a
#[1] 3 5 6
#$b
#[1] 3 1 0
或者使用purrr
的keep
和discard
purrr::keep(my_list, ~length(.) >= 3)
purrr::discard(my_list, ~length(.) < 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.