Skip to content
Prev 15192 / 15274 Next

apply a function to a data.frame column with condition

On Thu, 06 Mar 2025, Arnaud Gaboury writes:
Is the ticker you want to fetch data for always the
same?  If yes, then something like this could be
used. [I don't know/use binance, so with a 'dummy' of
your function.]

    get_btc_price <- function(my_time) {
        paste(42, my_time)
    }
    
    new.column <- mapply(
        function(symbol, mytime) {
            if (grepl("BTC$", symbol)) {
                get_btc_price(mytime)
            } else
                NA
        },
        portfolio$symbol,
        portfolio$time
    )

    ##                 BTCUSDT                  BTCUSDT 
    ##                      NA                       NA 
    ##                 ETHUBTC                  AAVEBTC 
    ##"42 2025-01-02 10:34:49" "42 2025-01-02 11:14:43" 
    ##                 ENAUSDT 
    ##                      NA
Message-ID: <8734fp1dij.fsf@enricoschumann.net>
In-Reply-To: <2954e4905995f8d9060e4f271406655d1654972a.camel@gmail.com> (Arnaud Gaboury's message of "Thu, 06 Mar 2025 18:24:33 +0100")