首页 > 解决方案 > 从数据框中提取特定单元格并将数据展平为单行

问题描述

我有一些看起来像这样的数据:

             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))

标签: rdplyr

解决方案


如果我们要选择特定的单元格,则使用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,则遍历listwithmap并应用相同的步骤

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)
})

推荐阅读