缺少列的R dplyr子集 [英] R dplyr subset with missing columns

查看:147
本文介绍了缺少列的R dplyr子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,想在新的 data.frame 中选择列。

I have the following code and would like to select columns into a new data.frame.

library(dplyr)
df = data.frame(
    Manhattan=c(1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), 
    Brooklyn=c(0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0), 
    The_Bronx=c(1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0), 
    Staten_Island=c(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), 
    "2012"=c("P", "P", "P", "P", "P", "P", "P", "P", "P", "P", "Q", "Q", "Q", "Q", "Q", "Q", "Q", "Q", "Q"), 
    "2013"=c("P", "P", "P", "P", "P", "P", "P", "P", "Q", "Q", "P", "P", "P", "P", "Q", "Q", "Q", "Q", "Q"), 
    "2014"=c("P", "P", "P", "Q", "Q", "P", "P", "Q", "Q", "Q", "Q", "Q", "P", "Q", "P", "P", "P", "Q", "Q"), 
    "2015"=c("P", "P", "P", "P", "P", "Q", "Q", "Q", "P", "Q", "P", "P", "Q", "Q", "Q", "Q", "Q", "Q", "Q"), check.names=FALSE)
df2 <- subset(df, select = c("Manhattan", "Queens", "The_Bronx"))

这会引发错误:

Error in [.data.frame`(x, r, vars, drop = drop) : 
   undefined columns selected

由于 df 中缺少女王一栏。我如何才能覆盖该错误,以便R继续仅使用曼哈顿和 The_Bronx列创建df2?

Because the column "Queens" is missing from df. How can I can override the error, so that R proceeds to create df2 with columns "Manhattan" and "The_Bronx" only?

非常重要:我的真实数据有数百个列,因此无法从命令 df2< -subset(df,select = c( Manhattan, Queens, The_Bronx))中手动删除 Queens之类的列/ code>(除非有窍门?)。有办法解决吗?谢谢。

Very important: My real data have hundreds of columns, so it is not doable to manually remove columns like "Queens" from the command df2 <- subset(df, select = c("Manhattan", "Queens", "The_Bronx")) (unless there is a trick for that?). Is there a way to solve this? Thank you.

推荐答案

在基数R中,可以使用 intersect 来仅选择存在的名称。

In base R, you can use intersect to select only the names which are present.

cols <- c("Manhattan", "Queens", "The_Bronx")
subset(df, select = intersect(names(df), cols))

#   Manhattan The_Bronx
#1          1         1
#2          1         1
#3          0         0
#4          1         0
#5          1         0
#6          1         0
#7          1         0
#8          0         0
#...
#....

或在其中使用 any_of dplyr

library(dplyr)
df %>% select(tidyselect::any_of(cols))

这篇关于缺少列的R dplyr子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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