缺少列的R dplyr子集
我有以下代码,希望将列选择到新的缺少列的R dplyr子集,r,dataframe,dplyr,subset,R,Dataframe,Dplyr,Subset,我有以下代码,希望将列选择到新的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,
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"))
因为df
中缺少列“Queens”。我怎样才能覆盖错误,使R继续创建只包含“曼哈顿”和“Theu Bronx”列的df2
非常重要:我的真实数据有数百列,因此无法从命令
df2中手动删除“Queens”等列。在base R中,可以使用intersect
仅选择存在的名称
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
#...
#....
在base R中,您可以使用intersect
仅选择存在的名称
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
#...
#....
我们也可以这样做
cols <- c("Manhattan", "Queens", "The_Bronx")
library(dplyr)
df %>%
select(matches(str_c(cols, collapse="|")))
cols%
选择(匹配(str_c(cols,collapse=“|”))
我们也可以这样做
cols <- c("Manhattan", "Queens", "The_Bronx")
library(dplyr)
df %>%
select(matches(str_c(cols, collapse="|")))
cols%
选择(匹配(str_c(cols,collapse=“|”))
Atidyverse
实施将是:
df2Atidyverse
df2哇!极好的非常感谢您的快速解决方案!:)您好,为什么my R返回“Error:'any_of'不是从“namespace:tidyselect”导出的对象?”@Negrito您可能需要升级到最新版本的tidyselect
。您的软件包版本('tidyselect')
是什么?我的是1.0.0。哇!极好的非常感谢您的快速解决方案!:)您好,为什么my R返回“Error:'any_of'不是从“namespace:tidyselect”导出的对象?”@Negrito您可能需要升级到最新版本的tidyselect
。您的软件包版本('tidyselect')
是什么?我的是1.0.0。