根据R中名称的向量删除列 [英] Removing columns based on a vector of names in R
问题描述
我有一个名为DATA
的data.frame
.使用 BASE R ,我想知道如何删除DATA
中任何名为以下任何变量的变量:ar = c("out", "Name", "mdif" , "stder" , "mpre")
?
I have a data.frame
called DATA
. Using BASE R, I was wondering how I could remove any variables in DATA
that is named any of the following: ar = c("out", "Name", "mdif" , "stder" , "mpre")
?
当前,我使用DATA[ , !names(DATA) %in% ar]
,但是虽然这会删除不需要的变量,但它会再次创建后缀为.1
的一些新的令人讨厌的变量.
Currently, I use DATA[ , !names(DATA) %in% ar]
but while this removes the unwanted variables, it again creates some new nuisance variables suffixed .1
.
提取后是否可以删除后缀?
After extraction, is it possible to remove just suffixes?
注意1::我们无权访问r
,唯一的输入是DATA
.
Note1: We have NO ACCESS to r
, the only input is DATA
.
注意2:这是玩具数据,值得赞赏的功能性解决方案.
Note2: This is toy data, a functional solution is appreciated.
r <- list(
data.frame(Name = rep("Jacob", 6),
X = c(2,2,1,1,NA, NA),
Y = c(1,1,1,2,1,NA),
Z = rep(3, 6),
out = rep(1, 6)),
data.frame(Name = rep("Jon", 6),
X = c(1,NA,3,1,NA,NA),
Y = c(1,1,1,2,NA,NA),
Z = rep(2, 6),
out = rep(1, 6)))
DATA <- do.call(cbind, r) ## DATA
ar = c("out", "Name", "mdif" , "stder" , "mpre") # The names for exclusion
DATA[ , !names(DATA) %in% ar] ## Current solution
#>
# X Y Z X.1 Y.1 Z.1 ## X.1 Y.1 Z.1 are automatically created but no needed
# 1 2 1 3 1 1 2
# 2 2 1 3 NA 1 2
# 3 1 1 3 3 1 2
# 4 1 2 3 1 2 2
# 5 NA 1 3 NA NA 2
# 6 NA NA 3 NA NA 2
推荐答案
理想情况下,列名应该是唯一的,但是如果要保留重复的列名,我们可以在提取后使用sub
删除suffixes
.
Ideally column names should be unique but if you want to keep duplicated column names, we can remove suffixes
using sub
after extraction
DATA1 <- DATA[ , !names(DATA) %in% ar]
names(DATA1) <- sub("\\.\\d+", "", names(DATA1))
DATA1
# X Y Z X Y Z
#1 2 1 3 1 1 2
#2 2 1 3 NA 1 2
#3 1 1 3 3 1 2
#4 1 2 3 1 2 2
#5 NA 1 3 NA NA 2
#6 NA NA 3 NA NA 2
这篇关于根据R中名称的向量删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!