簡體   English   中英

從拆分的列表中確定NA和無限(INF)值,並使包含INF的元素的NA值為NULL

[英]Determining NA and Infinite (INF) values from a list that is split and making elements containing INF, NA values NULL

嗨,我有一個列表已被用戶拆分。 清單的結構為

> lst
$A
timestamp user value
2011-01-01 A    1184437
2011-02-01 A    1197000
2011-03-01 A    1483965
2011-04-01 A    1248051
2011-05-01 A    1285838

$B
timestamp user value
2011-01-01 B    12315
2011-02-01 B    12325345
2011-03-01 B    1235223
2011-04-01 B    Inf
2011-05-01 B    Inf

$C
timestamp user value
2011-01-01 C    NA
2011-02-01 C    NA
2011-03-01 C    1181080
2011-04-01 C    1326289
2011-05-01 C    1264455

在運行時,我想確定列表中的任何元素是否包含INF或NA值。 如果是,則將元素的名稱存儲在其他位置,並使該元素在列表中為NULL。 我一直在嘗試使用is.infinite()來捕獲INF值,但是它無法正常工作,說明錯誤

invalid subscript type 'list'

使用的代碼:

NA_names <-  names(lst)[sapply(lst, function(x) sum(is.na(x)) > 0)]    
inf_names <- names(lst)[sapply(lst, function(x) sum(is.infinite(x)) > 0)]

有什么幫助或建議嗎? 由於sapply可與數據框一起使用,因此我不確定要使用哪種方法。

您可以使用purrr軟件包執行此purrr

library(purrr)

drops <- map(lst, 'value') %>% # extract the 'value' column from each data.frame
  keep(~ any(!is.finite(.))) %>% # keep only items with non-finite values
  names() # get the names of the remaining list items

lst[drops] <- NULL

purrr::map工作方式與lapply相同,不同之處在於它為您提供了方便的快捷方式,用於提取列表中的元素(例如使用字符串從data.frame中提取列,如示例中所示)。 purrr::keep遍歷列表,僅保留滿足您指定的邏輯條件的元素。

假設列表元素由data.frame組成,則嵌套的sapply類的東西應該可以工作。

# get the list elements that have any infinite value within
keepers <- !sapply(myList, function(i) any(sapply(i, is.infinite)))
keepers
    a     b     c 
 TRUE FALSE  TRUE 

# get new list
myNewList <- myList[keepers]

# print names of dropped list items
names(keepers)[keepers]
[1] "b"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM