R l oop xts участки - PullRequest
       29

R l oop xts участки

0 голосов
/ 05 мая 2020

Я застрял на, вероятно, простой проблеме: L oop на объектах xts.

Я хотел бы сделать четыре разных графика для элементов в корзине: basket <- cbind(AAPLG, GEG, SPYG, WMTG)

> head(basket)
           new.close new.close.1 new.close.2 new.close.3
2000-01-04 1.0000000   1.0000000   1.0000000   1.0000000
2000-01-05 1.0146341   0.9982639   1.0017889   0.9766755
2000-01-06 0.9268293   1.0115972   0.9856887   0.9903592
2000-01-07 0.9707317   1.0507639   1.0429338   1.0651532
2000-01-10 0.9536585   1.0503472   1.0465116   1.0457161
2000-01-11 0.9048780   1.0520833   1.0339893   1.0301664

Это моя идея, так как я не могу просто ввести i в качестве имени столбца :

   tickers <- c("AAPLG", "GEG", "SPYG", "WMTG")

par(mfrow=c(2,2))    
for (i in 1:4){
    print(plot(x = basket[, [i]], xlab = "Time", ylab = "Cumulative Return",
         main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
         minor.ticks = FALSE, col = "red"))
    }

Это ошибка, которую я получаю при запуске сценария:

Error: unexpected ',' in "     main = "Cumulative Returns","
>      minor.ticks = FALSE, col = "red"))
Error: unexpected ',' in "     minor.ticks = FALSE,"
> }
Error: unexpected '}' in "}"

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 05 мая 2020

Как уже упоминалось, удалите квадратные скобки вокруг i:

par(mfrow=c(2,2))    
for (i in 1:4){
    print(plot(x = basket[, i], xlab = "Time", ylab = "Cumulative Return",
         main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
         minor.ticks = FALSE, col = "red"))
}

Но еще лучше, назначьте имена с помощью cbind в построении объекта xts или переименуйте свой xts объект, например любой фрейм данных, затем перебирать имена для ссылок на столбцы и заголовков:

Plot

# PASS NAMES WITH cbind
basket <- cbind(AAPLG=APPLG, GEG=GEG, SPYG=SPYG, WMTG=WMTG)

# RENAME AFTER cbind
# basket <- cbind(AAPLG, GEG, SPYG, WMTG)
# colnames(basket) <- c("AAPLG", "GEG", "SPYG", "WMTG")

par(mfrow=c(2,2))
sapply(names(basket), function(col)
  print(plot(x = basket[, col], xlab = "Time", ylab = "Cumulative Return", data = basket,
             main = paste(col, "Cumulative Returns"), ylim = c(0.0, 3.5), 
             major.ticks= "years", minor.ticks = FALSE, col = "red"))
)

Plot Output

...