R:更改命名向量中的名称
R的命名向量非常方便,但是,我想组合两个包含系数估计值和这些估计值的标准误差的向量,并且两个向量具有相同的名称:
> coefficients_estimated
y0 Xit (Intercept)
1.1 2.2 3.3
> ses_estimated
y0 Xit (Intercept)
.04 .11 .007
如果我知道元素的顺序,这将很容易解决是肯定的,但这在我的脚本中并不能得到保证,所以我不能简单地执行 names(ses_estimated) <- 无论如何
。我想做的就是在每个名称的末尾添加“coef”或“se”,为此,我想出了一个我认为相当丑陋的黑客:
names(coefficients_estimated) <- sapply(names(coefficients_estimated),
function(name)return(paste(name,"coef",sep=""))
)
names(ses_estimated) <- sapply(names(ses_estimated),
function(name)return(paste(name,"se",sep=""))
)
有没有一种理想的方法来做到这一点?还是我必须坚持我所写的内容?
R's named vectors are incredibly handy, however, I want to combine two vectors which contain the estimates of coefficients and the standard errors for those estimates, and both vectors have the same names:
> coefficients_estimated
y0 Xit (Intercept)
1.1 2.2 3.3
> ses_estimated
y0 Xit (Intercept)
.04 .11 .007
This would be easy to solve if I knew what order the elements were in for sure, but this isn't guaranteed in my script, so I can't simply do names(ses_estimated) <- whatever
. All I want to do is add either "coef" or "se" to the end of each name, and to do this, I've come up with what I think is a pretty ugly hack:
names(coefficients_estimated) <- sapply(names(coefficients_estimated),
function(name)return(paste(name,"coef",sep=""))
)
names(ses_estimated) <- sapply(names(ses_estimated),
function(name)return(paste(name,"se",sep=""))
)
Is there an idomatic way to do this? Or am I going to have to stick with what I've written?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您使用
c()
组合向量,我不相信有一种“纯粹”的方法可以做到这一点。在上面的代码中,您甚至不需要使用
sapply
。只需paste(names(coefficients_estimated), "coef", sep="")
就会得到同样的结果。通过将名称应用于组合向量与单独向量,您还可以变得更简单。如果这些是数据帧,则
suffixes
参数将正是您想要的。Assuming you're combining the vectors using
c()
, I don't believe there's a "pure" way to do this.In your code above, you don't even need to use
sapply
. Justpaste(names(coefficients_estimated), "coef", sep="")
will get you the same thing. You can get a little simpler still by applying the names to the combined vector vs. separately.If these were data frames, the
suffixes
argument would be exactly what you want.setNames 在这里很有帮助:
setNames is helpful here: