英文:
How to write several columns in one colum in R
问题
我有一个数据框,大约有6000列和5500行。
数据框的第一列是日期("Timeframe"),其余列是不同股票的对数收益。
我现在想把所有股票列(它们的名称是它们各自的RICs)写入一个单独的列。但第一列(Timeframe)应该保留相应的对数收益。
这是一些示例数据:
Timeframe <- c("2001-01-01", "2001-01-02", "2001-01-03")
ABC.PK <- c(0.000987, 0.987389, 0.09784372842)
FDE.OQ <- c(43827, 849320, 748932)
HIK.O <- c(5438, 92889, 7492)
DF <- data.frame(Timeframe, ABC.PK, FDE.OQ, HIK.O)
为了更好地说明,这是我的当前数据框:
这是我想要的输出:
谁可以帮助我?
英文:
I have a data frame with roughly 6000 columns and 5500 rows.
The first column of my data frame is a Date ("Timeframe"), the rest of the columns are log returns for different stocks.
I know want to write all of the stock columns (their names are their respective RICs) into one single column. The first column (Timeframe) shall however remain with the respective log returns.
Here is some trial data:
Timeframe <- c(2001-01-01, 2001-01-02, 2001-01-03)
ABC.PK <- c(0,000987, 0,987389, 0,09784372842)
FDE.OQ <- c(43827, 849320, 748932)
HIK.O <- c(5438, 92889, 7492)
DF <- data.frame(Timeframe, ABC.PK, FDE.OQ, HIK.O)
To better illustrate it, this is my current data frame:
And this is my desired output:
Who can help me?
答案1
得分: 1
你可以使用 pivot_longer
函数:
library(tidyr)
library(dplyr)
DF %>%
pivot_longer(-Timeframe) %>%
rename(RIC = name, Value = value)
# 一个数据框: 18 × 3
Timeframe RIC Value
<dbl> <chr> <dbl>
1 1999 ABC.PK 0
2 1999 FDE.OQ 43827
3 1999 HIK.O 5438
4 1998 ABC.PK 987
5 1998 FDE.OQ 849320
6 1998 HIK.O 92889
7 1997 ABC.PK 0
8 1997 FDE.OQ 748932
9 1997 HIK.O 7492
10 1999 ABC.PK 987389
11 1999 FDE.OQ 43827
12 1999 HIK.O 5438
13 1998 ABC.PK 0
14 1998 FDE.OQ 849320
15 1998 HIK.O 92889
16 1997 ABC.PK 9784372842
17 1997 FDE.OQ 748932
18 1997 HIK.O 7492
英文:
You can use pivot_longer
:
library(tidyr)
library(dplyr)
DF %>%
pivot_longer(-Timeframe) %>%
rename(RIC = name, Value = value)
# A tibble: 18 × 3
Timeframe RIC Value
<dbl> <chr> <dbl>
1 1999 ABC.PK 0
2 1999 FDE.OQ 43827
3 1999 HIK.O 5438
4 1998 ABC.PK 987
5 1998 FDE.OQ 849320
6 1998 HIK.O 92889
7 1997 ABC.PK 0
8 1997 FDE.OQ 748932
9 1997 HIK.O 7492
10 1999 ABC.PK 987389
11 1999 FDE.OQ 43827
12 1999 HIK.O 5438
13 1998 ABC.PK 0
14 1998 FDE.OQ 849320
15 1998 HIK.O 92889
16 1997 ABC.PK 9784372842
17 1997 FDE.OQ 748932
18 1997 HIK.O 7492
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论