如果使用 R (tidyverse) 在数据框中丢失,则创建列

Create columns if missing in dataframe with R (tidyverse)

我有一个具有这种结构的 df

id 1 2 3 5 
1  1 0 2 0
2  3 4 1 0
3  1 1 0 2

我想要完成它,因为我需要它符合从 1 到 6 列的格式,因此预期结果将是

id 1 2 3 4 5 6 
1  1 0 2 0 0 0
2  3 4 1 0 0 0
3  1 1 0 0 2 0

这是一个示例 'missing' 在此示例中,列可以变化为 4 和 6,因此我们的想法是,如果缺少该列,它将被创建并用零填充。

谢谢!

您可以执行此操作的一种方法是重塑 long,使用 tidyr::complete 获取列名的范围,然后重塑 wide。由于新列的 id 未知,因此我也删除了 id = NA 行。

请注意,R 并不总是能很好地处理数字列名,并且它们不被视为句法。 https://stat.ethz.ch/R-manual/R-devel/library/base/html/make.names.html

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number.

但是如果我们告诉 R 不要检查,我们可以用数字字符串作为列名来创建数据框:

library(tidyverse)
data.frame(                 
  check.names = FALSE,          
           id = c(1L, 2L, 3L),
          `1` = c(1L, 3L, 1L),
          `2` = c(0L, 4L, 1L),
          `3` = c(2L, 1L, 0L),
          `5` = c(0L, 0L, 2L)
) %>% 
  pivot_longer(-id, names_transform = as.numeric) %>%
  complete(name = 1:6) %>%
  pivot_wider(names_from = name, values_from = value, values_fill = 0) %>%
  drop_na(id)

结果

# A tibble: 3 × 7
     id   `1`   `2`   `3`   `4`   `5`   `6`
  <int> <int> <int> <int> <int> <int> <int>
1     1     1     0     2     0     0     0
2     2     3     4     1     0     0     0
3     3     1     1     0     0     2     0