如果不存在则添加列 [英] Adding column if it does not exist

查看:35
本文介绍了如果不存在则添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of data frames with different variables. I want to read them into R and add columns to those that are short of a few variables so that they all have a common set of standard variables, even if some are unobserved.

换句话说......当列不存在时,有没有办法在tidyverse中添加NA的列?我当前的尝试适用于在列不存在的情况下添加新变量 (top_speed) 但在列已存在时失败 (mpg) - 它将所有观察值设置为第一个价值马自达RX4.

In other words... Is there a way to add columns of NA in the tidyverse when a column does not exist? My current attempt works for adding new variables where the column doesn't exist (top_speed) but fails when the column already exists (mpg) - it sets all observations to the first value 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

推荐答案

另一个不需要使用 tibble 的 add_column 创建辅助函数(或已经完成的 data.frame)的选项:

Another option that does not require creating a helper function (or an already complete data.frame) using tibble's add_column:

library(tibble)

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

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

这篇关于如果不存在则添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆