【发布时间】:2018-02-14 01:25:06
【问题描述】:
我试图对一个包含 278226 个元素的大列表进行子集化,每个元素(如下所示)也是一个列表,其中包含多个(39 到 50 之间)子元素(大小为 1 的具有不同名称的原子向量)。
> str(listings_England[9922])
List of 1
$ listing:List of 40
..$ agent_address : chr "35 John Street, Luton"
..$ agent_logo : chr "https://st.zoocdn.com/zoopla_static_agent_logo_(257607).png"
..$ agent_name : chr "Ashton Carter Homes"
..$ agent_phone : chr "020 8115 4543"
..$ category : chr "Residential"
..$ country : NULL
..$ country_code : chr "gb"
..$ county : NULL
..$ displayable_address : chr "Hatters Way Luton, Luton LU1"
..$ first_published_date: chr "2017-11-16 17:25:36"
..$ last_published_date : chr "2018-01-29 18:40:52"
..$ latitude : chr "51.88188"
..$ listing_id : chr "39336869"
..$ listing_status : chr "sale"
..$ longitude : chr "-0.43237194"
然后我提取“listing_id”等子元素如下:
> id1 <- sapply(listings_England, "[[", "listing_id")
Error in FUN(X[[i]], ...) : subscript out of bounds
> id3 <- sapply(listings_England[1:100000], "[[", "listing_id")
Error in FUN(X[[i]], ...) : subscript out of bounds
> id2 <- sapply(listings_England[1:50000], "[[", "listing_id")
>
> listings_England$listing_id
NULL
>
如您所见,它仅适用于最后一个(purrr::map 系列函数的问题相同)。我想知道这是否是这些功能的限制。而我目前的解决方案是:
id <- sapply(listings_England, function(x) x["listing_id"]) %>% as.numeric()
这里的问题是“[[”或“$”函数不适用于这个大列表,只有“[”有效。
【问题讨论】:
-
如果它适用于元素
1:50000但不适用于1:100000,我打赌在50000:100000范围内的元素没有listing_id财产,或者整个事情是NULL。 -
@JesseTweedle 是的,你是对的!它是 NULL 导致这个问题。谢谢!
-
列表很烦人,而且大的更糟糕,因为它们会抛出奇怪的错误,无法为您指明正确的方向。如果可以的话,我通常会尽快将它们转换为小标题(直接使用
enframe或bind_rows或与map结合使用)。 -
哦,还有两个建议:直接
bind_rows(listings_England),或者purrr:discard(listings_England, is.null)立即删除NULL元素。