如何在 R 中将列转置为行并确保行相应地重复?[复制]

How to transpose columns into rows and ensure repetition of rows accordingly in R? [duplicate]

提问人:Sri Sreshtan 提问时间:11/5/2023 更新时间:11/5/2023 访问量:44

问:

如何转置列并确保相应地重复行?

数据集包含以下数据:-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 数据集 Tidyverse 数据操作 转置

评论

1赞 TarJae 11/5/2023
用。.pivot_longer()library(tidyr) pivot_longer(df, cols = c(USD, EUR, JPY), names_to = "Currency", values_to = "Currency/CCY")
0赞 Sri Sreshtan 11/5/2023
在原始数据集中,实际上有近 30 列。在此示例中,我仅突出显示了三个。有没有办法根据列号修改列包含?
0赞 TarJae 11/5/2023
是的,1:30 或任何你想要的列。或者最好排除那些你不需要的-c(a, b, c, etc..)

答:

2赞 jkatam 11/5/2023 #1

使用 Base 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