首页 > 解决方案 > 为什么我在数据框中分隔行时遇到问题?

问题描述

我在分隔我正在使用的数据框中的行时遇到问题。

在我的数据框中,有一个名为 officialIndices 的列,我想用它来分隔行。此列存储一个数字列表,用作索引以指示哪些行具有相同的数据。例如:索引 2:3 表示行 2:3 具有相同的数据。

这是我正在使用的代码。

offices_list <- data_google$offices
offices_JSON <- toJSON(offices_list)
offices_from_JSON <-
  separate_rows(fromJSON(offices_JSON), officialIndices, convert = TRUE)

这就是我的office_list 框架的样子 这就是我的office_list 框架的样子

这是我尝试分隔行后的样子 分隔行后

我的代码在索引为 2:3 时工作正常,因为差异为 1。但是在像 7:10 这样的索引上,它将行分隔为 7 和 10,而不是执行 7、8、9、10,这就是我的方式希望它完成。我如何让我的代码像这样分隔行?

dput(head(offices_list)) 的输出

structure(list(position = c("President of the United States", 
"Vice-President of the United States", "United States Senate", 
"Governor", "Mayor", "Auditor"), divisionId = c("ocd-division/country:us", 
"ocd-division/country:us", "ocd-division/country:us/state:or", 
"ocd-division/country:us/state:or", "ocd-division/country:us/state:or/place:portland", 
"ocd-division/country:us/state:or/place:portland"), levels = list(
    "country", "country", "country", "administrativeArea1", NULL, 
    NULL), roles = list(c("headOfState", "headOfGovernment"), 
    "deputyHeadOfGovernment", "legislatorUpperBody", "headOfGovernment", 
    NULL, NULL), officialIndices = list(0L, 1L, 2:3, 4L, 5L, 
    6L)), row.names = c(NA, 6L), class = "data.frame")

标签: r

解决方案


这应该有效。我希望它也适用于更多行,因为我测试了大于 2 in 的范围officialIndices

首先,我提取了开始行和结束行,并使用它们的差异来确定需要多少行。然后tidyr::uncount()将添加那么多副本。

library(dplyr); library(tidyr)
data_sep <- data %>%
  separate(officialIndices, into = c("start", "end"), sep = ":") %>%
  # Use 1 row, and more if "end" is defined and larger than "start"
  mutate(rows = 1 + if_else(is.na(end), 0, as.numeric(end) - as.numeric(start))) %>%
  uncount(rows)

推荐阅读