I have have a data.frame that is 800x28000. I would like to spilt the column based on a pattern and bind the rows. However, I need to create a new column called "ticker" along the way.
Here is the data frame.
df1 = structure(list(AAPL.Price = c(20, 21), AAPL.Volume = c(100, 105
), MSFT.Price = c(30, 31), MSFT.Volume = c(150, 160)), class = "data.frame", row.names = c(NA,
-2L))
print(df1)
AAPL.Price AAPL.Volume MSFT.Price MSFT.Volume
1 20 100 30 150
2 21 105 31 160
I would like the final data frame to look like:
Price Volume Ticker
1 20 100 AAPL
2 21 105 AAPL
3 30 150 MSFT
4 31 160 MSFT
I have built a not so good work around. The answer I am looking for is a slight variation to the answer that Akrun provided here. Split Data Every N Columns and rbind Using R The only difference being, I need to create an extra column "Ticker" as I am binding the rows.
Here is my current work around.
library(foreach)
library(tidyverse)
ticker = c("AAPL", "MSFT")
rbind.table = function(ticker){
header = paste0("^", ticker)
df2 = df1[str_detect(names(df1), header)]%>%mutate(ticker = ticker)
names(df2) = c("Price", "Volume", "Ticker")
return(df2)
}
df2 = foreach(r = ticker, .packages = c("tidyverse", "stringr"), .combine = "bind_rows") %dopar% {rbind.table(r)}
print(df2)
Price Volume Ticker
1 20 100 AAPL
2 21 105 AAPL
3 30 150 MSFT
4 31 160 MSFT