Home > Enterprise >  Is there a simple way of reversing the dates in a dataframe in R?
Is there a simple way of reversing the dates in a dataframe in R?

Time:10-13

I have downloaded the daily prices for bitcoin as a .csv file, and the data is sorted from 2021-2017, but I want it to go from 2017 to 2021. My best solution was to reverse each column by indexing, but this is a bit time consuming with 10 columns per asset and at least 4 more assets to go. Is there a way to simply reverse the entire data set at once? I tried rev() and it just reversed the order of columns, which wasn't helpful.

BTC <- read.csv("Binance_BTCUSDT_d.csv", skip = 1)
  n1 <- nrow(BTC)
  BTC$date  <- as.Date(BTC$date[n1:1])
  BTC$open  <- BTC$open[n1:1]
  BTC$close <- BTC$close[n1:1]
  BTC$Volume.BTC <- BTC$Volume.BTC[n1:1]
  BTC_tradecount <- BTC$tradecount[n1:1]
  BTC$high <- NULL
  BTC$low <- NULL
  BTC$unix <- NULL
  BTC$symbol <- NULL
  BTC$Volume.USDT <- NULL
  BTC$tradecount <- NULL

I also had to remove some columns and did this "manually" as well. If there is any clever way to remove multiple columns at once, I would appreciate tips on this as well.

CodePudding user response:

For ordering rows, you can use this:

BTC <- BTC[order(BTC$date),]

To remove several columns at once, you can use the package dplyr:

library('dplyr')

BTC <- BTC %>% select(-high, -low, -unix, -symbol, -Volume.USDT, -tradecount)

If the column are ordered from high to tradecount, you can shorten it to:

BTC <- BTC %>% select(-(high:tradecount))
  • Related