[英]R: Using dplyr to remove a column named in a string contained in a variable,
I am creating a bunch of files. 我正在创建一堆文件。 I have a list of two letter names.
我有两个字母的名字的清单。 Each file includes a column with the same name as the file.
每个文件都包含与该文件同名的列。 I do a series of things to them, identifying both the file and the column with the name contained in a variable, sT.
我对他们执行了一系列操作,使用包含在变量sT中的名称来标识文件和列。 For example, I have a file called OH, and sT contains "OH".
例如,我有一个名为OH的文件,并且sT包含“ OH”。
The very last thing I want to do to the file is remove the eponymous column and return a file with the same name. 我要对该文件做的最后一件事是删除同名列并返回具有相同名称的文件。 I am trying to become fluent in tidy , language of the tidyverse , so I am trying to do this with select.
我正在尝试使tidyverse的语言整洁 ,流利,因此我尝试使用select做到这一点。
OH <- data.frame(X=1:2, OH=3:4)
I think this should work under nonstandard evaluation: 我认为这应该在非标准评估下起作用:
assign(sT, select(get(eval(sT)), -as.symbol(get(sT)))
where sT is "OH" and get(eval(sT)) is the file OH. 其中sT为“ OH”,而get(eval(sT))为文件OH。 And I think one of these should work, under standard evaluation:
我认为,其中一项应该在标准评估下起作用:
assign(sT, select(get(eval(sT)), - sT))
or 要么
assign(sT, select_(get(eval(sT)), paste0("-", sT)))
depending on whether select_
will accept the minus sign inside of the string. 取决于
select_
是否将接受字符串内的减号。 But none of them do, returning respectively: 但是它们都不做,分别返回:
Error in -as.symbol(sT) : invalid argument to unary operator
Error in eval(expr, envir, enclos) : object 'OH' not found
Error in eval(expr, envir, enclos) : object 'OH' not found
You need to use matches
您需要使用
matches
assign(sT, select(get(eval(sT)), -matches(sT)))
Edit: as alistaire points out, it should be as below in case there are other columns whose names contain OH
编辑:正如alistaire指出的,如果其他列的名称包含
OH
,则应如下所示
assign(sT,select(get(eval(sT)), -matches(paste0('^', sT, '$'))))
Doing it as below is probably more readable. 如下所述,这样做可能更具可读性。 It's also faster.
它也更快。
assign(sT, OH[which(names(OH) != sT)])
If you want it as a function to lapply
with here's one 如果你想把它当作一个函数来
lapply
与这里的一个
removecol <- function(string, data = F){
if(class(data) == 'logical') data <- get(eval(sT))
assign(sT, data[which(names(data) != sT)], envir = .GlobalEnv)
}
OH
# X OH
#1 1 3
#2 2 4
removecol(sT)
OH
# X
#1 1
#2 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.