如何调换列并确保行相应重复?
数据集
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 我们可以达到相同的结果
# 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