编写一个循环来拾取并合并列表中的重叠部分

Write a loop to pick up and merge overlapped part in a list

我有一个大列表 (list_1920),如下所示。

city01 <- data.frame("city" = "01", "gender" = c("female", "male"), "number" = c(12,20))
city02 <- data.frame("city" = "02", "gender" = c("female", "male"), "number" = c(50,40))
list2019 <- list(city01, city02)
names(list2019) = c("city01_2019", "city02_2019")
city01 <- data.frame("city" = "01", "gender" = c("female", "male"), "number" = c(60,80))
city02 <- data.frame("city" = "02", "gender" = c("female", "male"), "number" = c(120,90))
list2020 <- list(city01, city02)
names(list2020) = c("city01_2020", "city02_2020")
list_1920 <- list(list2019, list2020)
list_1920

感谢社区成员的帮助,我现在可以使用lapply获取不同年份的同一个城市的信息:

city01 <- lapply(list_1920, function(x) x$city01)
city02 <- lapply(list_1920, function(x) x$city02)

city01
#> [[1]]
#>   city gender number
#> 1   01 female     12
#> 2   01   male     20
#> 
#> [[2]]
#>   city gender number
#> 1   01 female     60
#> 2   01   male     80

city02
#> [[1]]
#>   city gender number
#> 1   02 female     50
#> 2   02   male     40
#> 
#> [[2]]
#>   city gender number
#> 1   02 female    120
#> 2   02   male     90

我现在想把这两个步骤结合起来,在一个循环中得到相同的结果,因为我需要根据上面的结果再做一步分析。我试过:

picklist <- tibble("city" = c("01", "02")
plist <- unique(picklist$city) # plist returns "01" and "02"
for (i in levels(plist)) {
  lst[[i]] <- lapply(list_1920, function(x) x$[[i]] 
# I hope this will return the same result shown above
  new <- merge(lst[[i]][[1]], lst[[i]][[2]])}
# lst[[i]][[1]] is what returned in city01 in the result shown above
# lst[[i]][[2]] is what returned in city02 in the result shown above

不幸的是,这不起作用。我收到一条调试消息 lst[[i]] <- lapply(list_1920, function(x) x$[[i]]

如果您能提供一些帮助,我们将不胜感激。非常感谢。

您可以使用 lapply 来挑选列表中的常量元素:

city01 <- lapply(list_1920, function(x) x$city01)
city02 <- lapply(list_1920, function(x) x$city02)

city01
#> [[1]]
#>   city gender number
#> 1   01 female     12
#> 2   01   male     20
#> 
#> [[2]]
#>   city gender number
#> 1   01 female     60
#> 2   01   male     80

city02
#> [[1]]
#>   city gender number
#> 1   02 female     50
#> 2   02   male     40
#> 
#> [[2]]
#>   city gender number
#> 1   02 female    120
#> 2   02   male     90

reprex package (v0.3.0)

于 2020-07-15 创建