r语言 - 如何加速此 json 字符串清理功能?



我将国家行政区的替代名称存储在 json 字符串中,并且我有一个清理 NA 和重复值的函数;但是,这是一个非常慢的函数,特别是当我在某些数据中有数万行时。我一直在使用整洁的语法,因为我最熟悉它。它可以工作,但是有人对如何优化此功能有想法吗?

下面是一些示例数据和函数:

library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)
library(tictoc)

data <- import(
'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
setclass = 'tibble'
)
cleanAlternateNames <- function(altNames) {
tic()
altNames %<>% lapply(function(x) {
if (!x %>% is.na()) {
x %>% fromJSON() %>% plyr::ldply(rbind) %>%
pivot_longer(-one_of('.id')) %>%
filter(!is.na(value),!value == 'NA') %>%
distinct(value, .keep_all = T) %>%
select(-name) %>%
pivot_wider(names_from = '.id', values_from = 'value') %>%
toJSON()
}
})
toc()
return(altNames)
}
data %<>%
mutate(AlternateNames = AlternateNames %>% str_replace_all('""','"') %>% 
cleanAlternateNames)

我修改了示例数据,以提供更好的范围来转换我正在尝试转换的内容。

感谢 Ian Campbell 和另一个用户的 map 的有用示例使用,我能够在我的代码中返回到我最初组合 json 列表的位置,并使用 map 函数删除重复项和重复项。这段代码明显更快,并且无需使用我用来尝试清理代码的函数。我在这里发布这个,以防有人有类似的问题。

library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)
# filters out duplicates from first string
.lfilter <- function(x1,x2){
nm <- names(x1)
x1 %<>%  unlist
x1 <- x1[!x1 %in% unlist(x2)] 
if(length(x1) > 0){
x1 %<>%
unname() %>% 
list() %>% set_names(nm)
}
return(x1)
}
# combines two columns that are in json format while removing duplicates
.combineJSONlists <- function(x){
x %<>% str_split("\|")
x1 <- x[[1]][1] %>% fromJSON()
x2 <- x[[1]][-1] %>% fromJSON() 
x1 <- map(x1, .lfilter, x2 = x2)
com <- x1  %>% c(x2) %>% toJSON()
return(com)
}
# load data
data <- import(
'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
setclass = 'tibble'
)
# combine new and old AlternateNames
data %<>%
mutate(
ISO = ISO %>% str_replace_all('""','"'),
AlternateNames = AlternateNames %>% str_replace_all('""','"') %>% 
paste0("|",ISO),
AlternateNames = AlternateNames %>%
map_chr(.combineJSONlists)) %>% 
select(-ISO)

最新更新