mardi 16 mars 2021

Replace 0's in column with another value from different column - R

I am working on creating a column called Quantity that holds the number of stocks either long or short in my portfolio.

  • The positions() fxn I have initialized returns a tibble (48 x 6): Instrument Symbol, averagePrice, longQuantity, shortQuantity, marketValue, assetType
  • [Positions function returns these columns 1

I have written a function to assign the individual tickers a long or short factor to keep track of which stocks are long/short.

positions() %>%

mutate(long.short =  factor(ifelse(positions()$longQuantity > 0, "long", "short")))

.

I am running into an error with my for loop which iterates through the df and will merge the columns into one, replacing values of 0 in longQuantity with the values from shortQuantity. `

    positions() %>%
        mutate(long.short =  factor(ifelse(positions()$longQuantity > 0, "long", "short"))) %>%
    #Code to merge long and short quantity into one column
        for(i in 1:nrow(positions())){
                if(positions()$longQuantity[i] == 0){
                        replace(positions()$longQuantity, i, positions()$shortQuantity[i])      
                } 
        }

`
  • This is the error,

    Error in for (. in i) 1:nrow(positions()) :

Any help or suggestions would be appreciated thanks! 4 arguments passed to 'for' which requires 3

Aucun commentaire:

Enregistrer un commentaire