how can i make my code more general? I want to be able to imput fast as many variables as i want.
asset1 <- asset_returns_xts[,1]
asset2 <- asset_returns_xts[,2]
asset3 <- asset_returns_xts[,3]
asset4 <- asset_returns_xts[,4]
asset5 <- asset_returns_xts[,5]
CodePudding user response:
You can use for loop:
for(i in 1:5){
assign(paste0("asset", i), asset_returns_xts[,i])
}
Apply family functions (lapply, sapply) may be faster.
CodePudding user response:
You may use list2env
.
list2env(setNames(d[1:3], paste0('asset', 1:3)), envir=.GlobalEnv)
ls()
# [1] "asset1" "asset2" "asset3" "d"
Data:
d <- data.frame(matrix(1:12, 3, 4))