我有一个 800x28000 的 data.frame。我想根据模式溢出列并绑定(bind)行。但是,我需要在此过程中创建一个名为“ticker”的新列。
这是数据框。
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
我希望最终的数据框看起来像:
Price Volume Ticker
1 20 100 AAPL
2 21 105 AAPL
3 30 150 MSFT
4 31 160 MSFT
我建立了一个不太好的解决方案。我正在寻找的答案与 Akrun 在这里提供的答案略有不同。 Split Data Every N Columns and rbind Using R唯一的区别是,我需要在绑定(bind)行时创建一个额外的列“Ticker”。
这是我目前的工作。
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
最佳答案
一个 dplyr
和 tidyr
可能是:
df1 %>%
rowid_to_column() %>%
gather(var, val, -rowid) %>%
separate(var, c("Ticker", "unit")) %>%
spread(unit, val) %>%
select(-rowid)
Ticker Price Volume
1 AAPL 20 100
2 AAPL 21 105
3 MSFT 30 150
4 MSFT 31 160
关于r - 按列模式和绑定(bind)行拆分 data.frame R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57876735/