将一个列表中的名称分配给另一个列表
我得到了一堆动态创建的回归,存储在一些名为“回归”的列表中。现在我想有效地重命名它们的系数。到目前为止,我所拥有的是这个有效的循环:
for (i in 1:length(params[,1])){
names(regressions[[i]]$coefficients)[pos] <- paste(params[i,1],".lag",params[i,2],sep="")
}
我已经尝试了很长一段时间,以在函数的帮助下更普遍地完成此操作,因为这不是我拥有的唯一回归列表。然而我无法让其他任何东西发挥作用。这里还有一些其他尝试,基本上基于 lapply:
correctNames <- function(reglist,namevec,pos){
names(reglist[[i]]$coefficients)[pos] <- as.character(namevec)
}
lapply(regressions,correctNames(reglist,namevec,pos),
reglist=regressions,namevec=params[,1],pos=2)
另一种尝试是编写一个带有 for 循环的函数,该函数也可以像 print 显示的那样在内部工作,但不会全局分配名称(存储回归列表的位置)。
correctNames <- function(reglist,pos,namevec){
for (i in 1:length(params[,1])){
names(reglist[[i]]$coefficients)[pos] <- paste(namevec,".lag",namevec,sep="")
}
#this test proves it's work inside the function...
print(reglist[[10]]
}
啊,让我休息一下。
I got a bunch dynamically created regressions stored in some list called regressions
. Now I´d like to rename their coefficients efficiently. What I have so far is this loop that works:
for (i in 1:length(params[,1])){
names(regressions[[i]]$coefficients)[pos] <- paste(params[i,1],".lag",params[i,2],sep="")
}
I've been trying for quite a while to get this done a little more generally with the help of a function, cause this not the only list of regressions I have. However I could not get anything else to work. Here a few other tries basically based on lapply:
correctNames <- function(reglist,namevec,pos){
names(reglist[[i]]$coefficients)[pos] <- as.character(namevec)
}
lapply(regressions,correctNames(reglist,namevec,pos),
reglist=regressions,namevec=params[,1],pos=2)
Another try was to write a function with a for loop which also works internally as print shows but does not assign the names globally (where the regressions list is stored).
correctNames <- function(reglist,pos,namevec){
for (i in 1:length(params[,1])){
names(reglist[[i]]$coefficients)[pos] <- paste(namevec,".lag",namevec,sep="")
}
#this test proves it's work inside the function...
print(reglist[[10]]
}
Ah, gimme a break.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“正确名称”函数的第一个版本中没有“i”;并且您可能没有意识到您没有将其分配给“回归”,而只是分配给回归对象的副本。尝试一下:
在看到 Ramnath 的注释并注意到代码确实有效但为“params”提供了不稳定的名称之后,我查看了 params 并发现它是一个因素,因此更改了
mapply< 中的参数/code> 调用
as.character(params[,1])
。There's no "i" inside that first version of "correctNames" function; and you probably don't realize that you are not assigning it to "regressions", only to a copy of the regression object. Try instead:
After seeing the note from Ramnath and noticing that the code did work but was giving flaky names for the "params" I looked at params and saw that it was a factor, and so changed the argument in the
mapply
call toas.character(params[,1])
.如果这是您之前问题的后续问题,那么这就是我要做的
这给了你
If this is a follow up to your earlier question, then here is what I would do
This gives you