本文介绍了当一些列名可能不存在时,使用data.table :: setnames()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个脚本返回一个 data.table
,它将包含一组列。我想重命名这些列,但 setnames
断开,如果不是所有的存在。有没有什么办法重命名没有循环+错误捕获或与现有的名称相交?
iris.dt< - data.table (iris)
#第一次工作正常
setnames(iris.dt,c(Sepal.Length,Sepal.Width),c(length,width))
#第二次失败,因为列不再存在
setnames(iris.dt,c(Sepal.Length,Sepal.Width),c(length,width))
#setnames中的错误(iris.dt,c(Sepal.Length,Sepal.Width),c(length,
#:列名中未找到old项:Sepal。 Length,Sepal.Width
像 setnames(...,allow =
解决方案
另一种从arunsrinivasan的建议改编自的建议:
Setnames< - function(x,old,new,allow.absent.cols = F){
if(!allow.absent.cols){
setnames(x,old,new)
} else {
ix< - match(names(x),old,0L)
setnames(x,old [ix],new [ix])
}
}
I have a script returning a data.table
which will contain a set of columns. I'd like to rename some of these columns, but setnames
breaks if not all are present. Is there any way to rename without looping+error catching or intersecting against existing names?
iris.dt <- data.table(iris)
# First time works fine
setnames(iris.dt, c("Sepal.Length", "Sepal.Width"), c("length", "width"))
# Second time fails because columns no longer exist
setnames(iris.dt, c("Sepal.Length", "Sepal.Width"), c("length", "width"))
# Error in setnames(iris.dt, c("Sepal.Length", "Sepal.Width"), c("length",
# :Items of 'old' not found in column names: Sepal.Length,Sepal.Width
Something like setnames(..., allow=T)
would be ideal.
Edit: Filed this as a FR on Github.
解决方案
Another approach adapted from arunsrinivasan's suggestion on the Github FR:
Setnames <- function(x, old, new, allow.absent.cols=F) {
if (!allow.absent.cols) {
setnames(x, old, new)
} else {
ix <- match(names(x), old, 0L)
setnames(x, old[ix], new[ix])
}
}
这篇关于当一些列名可能不存在时,使用data.table :: setnames()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!