r - 从数据框中提取特定单元格并将数据展平为单行
问题描述
我有一些看起来像这样的数据:
Variable_Nombre_1 Variable_Codigo_1 Variable_Nombre_2 Variable_Codigo_2
1 Dato base <NA> Tipo de dato <NA>
2 Alella sección 01004 0800301004 Secciones SECC
3 Fuente de ingreso: pensiones <NA> Distribución de la fuente de ingresos <NA>
我想提取数据的特定单元格。
要提取的细胞:
x[2, 1]
x[3, 1]
x[2, 2]
x[2, 3]
x[3, 3]
pivot_wider
然后使用提取的单元格展平数据。我正在尝试使用管道运算符执行此操作,因为列表中有许多数据框,我想map
覆盖并提取这些单元格,然后展平数据。
数据:
d <- structure(list(Variable_Nombre_1 = c("Dato base", "Alella sección 01004",
"Fuente de ingreso: pensiones"), Variable_Codigo_1 = c(NA, "0800301004",
NA), Variable_Nombre_2 = c("Tipo de dato", "Secciones", "Distribución de la fuente de ingresos"
), Variable_Codigo_2 = c(NA, "SECC", NA)), class = "data.frame", row.names = c(NA,
-3L))
解决方案
如果我们要选择特定的单元格,则使用cbind
行/列向量索引来提取为vector
v1 <- d[cbind(c(2, 3, 2, 2, 3), c(1, 1, 2, 3, 3))]
然后,我们可以使用as.data.frame.list
将向量转换为单行
as.data.frame.list(v1)
或者命名vector
然后使用as_tibble_row
library(tibble)
names(v1) <- paste0("V", seq_along(v1))
as_tibble_row(v1)
# A tibble: 1 x 5
V1 V2 V3 V4 V5
<chr> <chr> <chr> <chr> <chr>
1 Alella sección 01004 Fuente de ingreso: pensiones 0800301004 Secciones Distribución de la fuente de ingresos
如果这需要在 a 中完成list
,则遍历list
withmap
并应用相同的步骤
library(purrr)
library(dplyr)
library(stringr)
map(lst1, ~ {
v1 <- .x[cbind(c(2, 3, 2, 2, 3), c(1, 1, 2, 3, 3))]
names(v1) <- str_c("V", seq_along(v1))
as_tibble_row(v1)
})
推荐阅读
- postgresql-9.3 - 为什么同一列上的索引大小不同
- c++ - 编码大于原文:How to take a strings of zero and one and write them as actual bytes to file
- javascript - 如何将日期时间与 10 分钟进行比较?
- javascript - 尝试将项目添加到 localStorage 但陷入无休止的刷新地狱
- java - 带有 Maven 集成测试的 GitLab CI - Java
- r - 决策树问题:为什么 tree() 不选择节点的所有变量
- java - 比较方法违反了它的一般合同——但我可能想要?
- python - 将命令行参数传递给集成测试
- java - 设置数组
- javascript - 将服务工作者的数据保存到文本文件中