简体   繁体   English

从 R 中的列表中提取信息

[英]Extract info from a list in R

I need to extract specific information from a list in R. My data is 'Benford' object and doesn't seem to be coercible using as_tibble()我需要从 R 中的列表中提取特定信息。我的数据是“Benford”object 并且似乎无法使用as_tibble()进行强制转换

My data looks as follows:我的数据如下所示:

library(dplyr)
library(purrr)
library(benford.analysis)

# read data
data = read.csv("https://www2.census.gov/programs-surveys/popest/datasets/2010-2019/counties/totals/co-est2019-alldata.csv", header = T)

# ONLY SELECT THE NUMERIC COLUMN
x <- data %>% 
  select(CENSUS2010POP)

# SPLIT THE DATA INTO TWO GROUPS
x$CITY <- "CITY_A"
x[1500:3193,2] <- "CITY_B"

# SPLIT THE DATA ON THE CITY VARIABLE
dat_list <- split(x,x$CITY)

# APPLY THE BENFORD ANALYSIS TO THE NUMERICAL VALUES PER GROUP
output <- map(dat_list, ~benford(number.of.digits = 1, discrete = TRUE, sign = "positive", data = .x$CENSUS2010POP))

I wish to create a data frame with the CITY name ie CITY_A in one column and the $ MAD.conformity in another for each element in the list.我希望为列表中的每个元素创建一个带有CITY名称的数据框,即一列中的CITY_A和另一列中的$ MAD.conformity

Any help on how I can pull these elements from my list and store them in a data frame?关于如何从列表中提取这些元素并将它们存储在数据框中的任何帮助?

You can use purrr::map_dfr() to extract MAD.conformity on each iteration, row-bind the results, and add an .id column containing the names of each element of dat_list .您可以使用purrr::map_dfr()在每次迭代中提取MAD.conformity ,行绑定结果,并添加一个包含dat_list每个元素名称的.id列。 Since dat_list was created by split ting on CITY , the names already correspond to the levels of CITY .由于dat_list是通过在CITYsplit创建的,因此名称已经对应于CITY的级别。 (I'm not familiar with the structure of Benford objects, so you may have to tweak the $MAD.conformity index.) (我不熟悉Benford对象的结构,因此您可能需要调整$MAD.conformity索引。)

output <- map_dfr(
  dat_list,
  ~ benford(
      number.of.digits = 1, 
      discrete = TRUE, 
      sign = "positive", 
      data = .x$CENSUS2010POP
    )$MAD.conformity,
  .id = "CITY"
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM