我有一些代码,我写了一段时间,在印刷中使用了4个投资组合。我想修改此代码以使用与我在MySymbols列表中定义条目一样多的投资组合。在下面的代码中,我首先展示了过去有效的方法,它明确地写出了4个投资组合的名称。在第二部分中,我尝试将其转换为一个循环,其中名称是动态构造的。该名称似乎是正确的,但R找不到投资组合,我看到警告信息:
1: In rm(Str1, pos = .blotter) : object 'Str1' not found
2: In rm(Str1, pos = .blotter) : object 'Str1' not found
3: In rm(Str1, pos = .blotter) : object 'Str1' not found
4: In rm(Str1, pos = .blotter) : object 'Str1' not found
找不到或删除投资组合:
> ls(.blotter)
[1] "portfolio.Port1" "portfolio.Port2" "portfolio.Port3" "portfolio.Port4"
我在这里做错了什么?如何让R使用我在Str1中构建的名称?
library(blotter)
Date_Start = "2000-01-01"
InitialEquity = 100000
currency("USD")
MyPortfolios = c("Port1", "Port2", "Port3", "Port4")
MySymbols = list()
MySymbols[[1]]= c("AAPL","GOOG")
MySymbols[[2]]= c("BAC","GS")
MySymbols[[3]]= c("CVX","XOM")
MySymbols[[4]]= c("TWTR","FB")
CashSymbol = "SHY"
ls(.blotter)
suppressWarnings(rm("account.Test1", pos = .blotter))
suppressWarnings(rm("portfolio.Port1", pos = .blotter))
suppressWarnings(rm("portfolio.Port2", pos = .blotter))
suppressWarnings(rm("portfolio.Port3", pos = .blotter))
suppressWarnings(rm("portfolio.Port4", pos = .blotter))
ls(.blotter)
initPortf(MyPortfolios[1], as.list( c(MySymbols[[1]], CashSymbol)), initDate = Date_Start)
initPortf(MyPortfolios[2], as.list( c(MySymbols[[2]], CashSymbol)), initDate = Date_Start)
initPortf(MyPortfolios[3], as.list( c(MySymbols[[3]], CashSymbol)), initDate = Date_Start)
initPortf(MyPortfolios[4], as.list( c(MySymbols[[4]], CashSymbol)), initDate = Date_Start)
initAcct("Test1", MyPortfolios, initDate = Date_Start, initEq = InitialEquity)
ls(.blotter)
# Do the same thing in a loop
NumPorts = length(MySymbols)
MyPorts=NULL
suppressWarnings(rm("account.Test1", pos = .blotter))
for (i in 1:NumPorts){
stock(MySymbols[[i]], currency = "USD", multiplier = 1)
MyPorts = c(MyPorts, paste0("Port",i))
}
ls(.blotter)
for (i in 1:NumPorts){
Str1 = paste0("portfolio.", MyPorts[i])
print(Str1)
# suppressWarnings(rm(Str1, pos = .blotter))
rm(Str1, pos = .blotter)
}
ls(.blotter)
答案 0 :(得分:3)
以下是问题的说明
> e1 <- new.env(parent = baseenv()) # create a new environment e1
> assign("obj", 1, envir = e1) # create object 'obj' in e1
> ls(e1)
[1] "obj"
> str1 <- "obj" # character vector containing "obj" (in the global environment)
> rm(str1, envir = e1) # this doesn't work
Warning message:
In rm(str1, envir = e1) : object 'str1' not found
> ls(e1)
[1] "obj"
这种方法不起作用,因为rm
的第一个参数必须是对象本身的名称。 str1
中没有对象e1
。
如果要使用字符向量,则必须使用list
参数:
> rm(list = str1, envir = e1)
> ls(e1)
character(0)