如何在 R 中将列转置为行并确保相应的行重复?

问题描述 投票:0回答:1

如何调换列并确保行相应重复?

数据集

df
具有以下数据:-

Date       Year  Month Day USD  EUR JPY
1994-1-1    1994  1     1   10  20   5
1995-1-1    1995  1     1   12  30   10

预期输出是:-

Date       Year Month Day Currency Currency/CCY
1994-1-1   1994 1     1   USD      10
1994-1-1   1994 1     1   EUR      20
1994-1-1   1994 1     1   JPY      5
1995-1-1   1995 1     1   USD      12
1995-1-1   1995 1     1   EUR      30
1995-1-1   1995 1     1   JPY      10
r dataset tidyverse data-manipulation transpose
1个回答
0
投票

使用基数 r 我们可以达到相同的结果

# Reshape the data
data_long <- reshape(data, idvar = c("Date", "Year", "Month", "Day"), varying = list(c("USD", "EUR", "JPY")), direction = "long", times = c("USD", "EUR", "JPY"), v.names = "Value")

# Reset column names
colnames(data_long) <- c("Date", "Year", "Month", "Day", "Currency", "Value")

# Order the data by Date
data_long[order(data_long$Date), ]

# covert the date to numeric date
data_long$Date <- as.Date(data_long$Date)

# drop the row names
rownames(data_long) <- NULL

# Output

        Date Year Month Day time Value
1 1994-01-01 1994     1   1  USD    10
2 1995-01-01 1995     1   1  USD    12
3 1994-01-01 1994     1   1  EUR    20
4 1995-01-01 1995     1   1  EUR    30
5 1994-01-01 1994     1   1  JPY     5
6 1995-01-01 1995     1   1  JPY    10
© www.soinside.com 2019 - 2024. All rights reserved.