繁体   English   中英

使用 for 循环创建新列,但我想在循环中这些新列的每个名称中添加“.Corr”。 我怎样才能做到这一点?

[英]make new columns with for loop but i want to add “.Corr” to each name of these new columns in the loop. How can i do that?

最后三列是从循环中生成的。 $PFN Date Open High Low Close Volume Adjusted Return HYG TLT SPY 1 2020-01-02 10.62 10.62 10.58 10.58 267700 10.231670 NA 0.6840342 0.043489 0.656935 2 2020-01-03 10.59 10.69 10.58 10.68 351800 10.328378 0.94518 0.6840342 0.043489 0.656935 3 2020-01- 06 10.66 10.73 10.66 10.73 318400 10.376730 0.46816 0.6840342 0.043489 0.656935 4 2020-01-07 10.71 10.71 10.76 10.76 10.70 10.71

但我想实现这个

$PFN Date Open High Low Close Volume Adjusted Return HYG.Corr TLT.Corr SPY.Corr 1 2020-01-02 10.62 10.62 10.58 10.58 267700 10.231670 NA 0.6840342 0.043489 0.656935 2 2020-01-03 10.59 10.69 10.58 10.68 351800 10.328378 0.94518 0.6840342 0.043489 0.656935 3 2020-01-06 10.66 10.73 10.66 10.73 318400 10.376730 0.46816 0.6840342 0.043489 0.656935 4 2020-01-07 10.71 10.76 10.70 10.71 261500 10.357388 -0.18639 0.6840342 0.043489 0.656935

一切都应该在 for 循环中完成!

如果数据集对象被命名为“PFN”、“PFP”等, get对象的值,然后将这些列重命名为首选值并将其重新assign (不建议在全局环境中创建多个对象)。 最好将其列在list

objs <- c('PFN', 'PFP')
 for(obj in objs){
    tmp <- get(obj)
    nm1 <- c("HYG", "TLT", "SPY")
    names(tmp)[names(tmp) %in% nm1] <- paste0(nm1, ".Corr")
    assign(obj, tmp)
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM