r - 为什么我在数据框中分隔行时遇到问题?
问题描述
我在分隔我正在使用的数据框中的行时遇到问题。
在我的数据框中,有一个名为 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)
我的代码在索引为 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")
解决方案
这应该有效。我希望它也适用于更多行,因为我测试了大于 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)
推荐阅读
- rust - 为什么边缘触发的 epoll 循环会在 HTTP 负载测试结束时冻结?
- java - 强制 AssertJ 将类视为对象而不是 Iterables
- regex - 可被 4 整除的二进制数的正则表达式
- c++ - 在 C++ 中为给定日期添加天数
- c - 无法输入字符串
- react-native - 运行 react-native run-android 时出现问题
- react-native - expo.constants 到底是什么?
- c - 如何让 fscanf 读取数据以“;”分隔的文件?
- python - Linux终端执行Python脚本的方式与空闲不同
- javascript - 如何让Parent DIV的Child DIV充当Parent DIV