Reputation: 1453
I have a problem replace the column name by the dataframe name with a map-function. I have 25 dataframes with cryptocurrency time series data.
ls(pattern="USD")
[1] "ADA.USD" "BCH.USD" "BNB.USD" "BTC.USD" "BTG.USD" "DASH.USD" "DOGE.USD" "EOS.USD" "ETC.USD" "ETH.USD" "IOT.USD"
[12] "LINK.USD" "LTC.USD" "NEO.USD" "OMG.USD" "QTUM.USD" "TRX.USD" "USDT.USD" "WAVES.USD" "XEM.USD" "XLM.USD" "XMR.USD"
[23] "XRP.USD" "ZEC.USD" "ZRX.USD"
Every object is a dataframe which stands for a cryptocurrency expressed in USD. And every dataframe has 2 clomuns: Date and Close (Closing price). For example: the dataframe "BTC.USD" stands for Bitcoin in USD:
head(BTC.USD)
# A tibble: 6 x 2
Date Close
1 2015-12-31 430.
2 2016-01-01 434.
3 2016-01-02 434.
4 2016-01-03 431.
5 2016-01-04 433.
Now I want to replace the name of the second column ("Close") by the name of the dataframe ("BTC.USD")
For this case I used the following code:
colnames(BTC.USD)[2] <-deparse(substitute(BTC.USD))
And this code works as I imagined:
head(BTC.USD)
# A tibble: 6 x 2
Date BTC.USD
1 2015-12-31 430.
2 2016-01-01 434.
3 2016-01-02 434.
Now I am trying to rename all "Close"-columns for all 25 dataframes of cryptocurrency data with a map-function:
names_of_dataframes <- ls.str(mode = "list")
map(names_of_dataframes, colnames(x)[2] <- names_of_dataframes[[i]])
But it doesn't work. Can someone help me?
Upvotes: 2
Views: 588
Reputation: 887241
We get the datasets into list
with mget
, loop through the list
with imap
, rename
the 2nd column with .y
which gives the data.frame
object name
library(tidyverse)
mget(ls(pattern="USD")) %>%
imap(~ {nm1 <- .y
.x %>%
rename_at(2, ~ nm1) })
Upvotes: 2