如果列不存在则添加

问题描述 投票:0回答:9

我有一堆具有不同变量的数据框。我想将它们读入 R 并将列添加到那些缺少一些变量的列中,以便它们都具有一组通用的标准变量,即使有些变量未被观察到。

换句话说...当列不存在时,有没有办法在 tidyverse 中添加

NA
的列?我当前的尝试适用于在列不存在的情况下添加新变量 (
top_speed
),但在列已存在时失败 (
mpg
) - 它将所有观察值设置为第一个值
Mazda RX4

library(tidyverse)
mtcars %>%
  as_tibble() %>%
  rownames_to_column("car") %>%
  mutate(top_speed = ifelse("top_speed" %in% names(.), top_speed, NA),
         mpg = ifelse("mpg" %in% names(.), mpg, NA)) %>%
  select(car, top_speed, mpg, everything())

# # A tibble: 32 x 13
#                  car top_speed   mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#                <chr>     <lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#  1         Mazda RX4        NA    21     6 160.0   110  3.90 2.620 16.46     0     1     4     4
#  2     Mazda RX4 Wag        NA    21     6 160.0   110  3.90 2.875 17.02     0     1     4     4
#  3        Datsun 710        NA    21     4 108.0    93  3.85 2.320 18.61     1     1     4     1
#  4    Hornet 4 Drive        NA    21     6 258.0   110  3.08 3.215 19.44     1     0     3     1
#  5 Hornet Sportabout        NA    21     8 360.0   175  3.15 3.440 17.02     0     0     3     2
#  6           Valiant        NA    21     6 225.0   105  2.76 3.460 20.22     1     0     3     1
#  7        Duster 360        NA    21     8 360.0   245  3.21 3.570 15.84     0     0     3     4
#  8         Merc 240D        NA    21     4 146.7    62  3.69 3.190 20.00     1     0     4     2
#  9          Merc 230        NA    21     4 140.8    95  3.92 3.150 22.90     1     0     4     2
# 10          Merc 280        NA    21     6 167.6   123  3.92 3.440 18.30     1     0     4     4
r dataframe dplyr purrr
9个回答
47
投票

另一个选项,不需要使用 tibble 的

add_column
创建辅助函数(或已经完成的 data.frame):

library(tibble)

cols <- c(top_speed = NA_real_, nhj = NA_real_, mpg = NA_real_)

add_column(mtcars, !!!cols[setdiff(names(cols), names(mtcars))])

20
投票

我们可以创建一个辅助函数来创建列

fncols <- function(data, cname) {
  add <-cname[!cname%in%names(data)]

  if(length(add)!=0) data[add] <- NA
  data
}
fncols(mtcars, "mpg")
fncols(mtcars, c("topspeed","nhj","mpg"))

14
投票

您可以像这样使用

rowwise
功能:

library(tidyverse)
mtcars %>%
  tbl_df() %>%
  rownames_to_column("car") %>%
  rowwise() %>%
  mutate(top_speed = ifelse("top_speed" %in% names(.), top_speed, NA),
         mpg = ifelse("mpg" %in% names(.), mpg, NA)) %>%
  select(car, top_speed, mpg, everything())

7
投票

如果您有一个包含要检查的所有名称的空数据框,则可以使用

bind_rows
添加列。

我使用

purrr:map_dfr
使用适当的列名称创建空
tibble

columns = c("top_speed", "mpg") %>%
     map_dfr( ~tibble(!!.x := logical() ) )

# A tibble: 0 x 2
# ... with 2 variables: top_speed <lgl>, mpg <lgl>

bind_rows(columns, mtcars)

# A tibble: 32 x 12
   top_speed   mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
       <lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1        NA  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
 2        NA  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4
 3        NA  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1

5
投票

根据 Hadley (2023),我们应该使用

dplyr::bind_rows()
和空的 tibble。

# Case when column exists
dplyr::tibble(x='a',y='b') %>% dplyr::bind_rows(dplyr::tibble(y=character()))
# Case when column does not exist
dplyr::tibble(x='a') %>% dplyr::bind_rows(dplyr::tibble(y=character()))

原始答案(从 dplyr_1.1.0 开始已过时): 或者,您可以将

dplyr::union_all()
与空小标题一起使用。

# Case when column exists
dplyr::tibble(x='a',y='b') %>% dplyr::union_all(dplyr::tibble(y=character()))
# Case when column does not exist
dplyr::tibble(x='a') %>% dplyr::union_all(dplyr::tibble(y=character()))

3
投票

尝试以下方法,

library(tidyverse)

mtcars %>%
  tbl_df() %>%
  rownames_to_column("car") %>%
  mutate(top_speed = if ("top_speed" %in% names(.)){return(top_speed)}else{return(NA)},
         mpg = if ("mpg" %in% names(.)){return(mpg)}else{return(NA)}) %>%
  select(car, top_speed, mpg, everything())
# A tibble: 32 x 13
                 car top_speed   mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
               <chr>     <lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1         Mazda RX4        NA  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
 2     Mazda RX4 Wag        NA  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4
 3        Datsun 710        NA  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1
 4    Hornet 4 Drive        NA  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
 5 Hornet Sportabout        NA  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2
 6           Valiant        NA  18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1
 7        Duster 360        NA  14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4
 8         Merc 240D        NA  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2
 9          Merc 230        NA  22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2
10          Merc 280        NA  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4
# ... with 22 more rows

我认为 ifelse() 不会从对象继承类。


1
投票

如果您已经有一个包含所有必需列的数据框,请说

library(tidyverse)  

df_with_required_columns = 
      mtcars %>% 
      mutate(top_speed = NA_real_) %>%
      select(top_speed, mpg)

然后你可以简单地

bind_rows
过滤掉所有行:

mtcars %>%
  rownames_to_column("car") %>%
  bind_rows( df_with_required_columns %>% filter(F) ) %>%
  select(car, top_speed, mpg, everything())

请注意,缺失的列将采用

df_with_required_columns
中的类型。


0
投票

您可以将新 data.frame 的列与填充 NA 的假完整 data.frame 绑定,重命名重复的列,然后仅过滤原始名称。

# your default complete vector of col names
standard.variables = names(mtcars)
# prep
default=mtcars %>% mutate_all(.funs=function(x) NA)
# treat with a data.frame missing 3 columns
test=mtcars %>% select(-mpg, -disp, -am)
bind_cols(test, default) %>% setNames(make.names(names(.), unique=TRUE)) %>% 
  select_(.dots=standard.variables) %>% head(2)
####    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#### 1  NA   6   NA 110  3.9 2.620 16.46  0 NA    4    4
#### 2  NA   6   NA 110  3.9 2.875 17.02  0 NA    4    4

0
投票

基于@Joris C. 的回答。这是一个管道友好的解决方案,不需要预先创建

cls
向量。

mtcars %>%
  # an inline anonymous function to add the needed columns
  (function(.df){
    cls <- c("top_speed", "nhj") # columns I need
    # adding cls columns with NAs if not present in the piped data.frame
    .df[cls[!(cls %in% colnames(.df))]] = NA
    return(.df)
  })
© www.soinside.com 2019 - 2024. All rights reserved.