我有一个数据帧:
Year var1 var2 var3
1 "2021" "19,080" "15,918" "11,502"
2 "2020" "19,367" "15,870" "11,302"
我想让它看起来像这样:
Year Var value
1 2021 var1 19,080
2 2021 var2 15,918
3 2021 var3 11,502
4 2020 var1 19,367
5 2020 var2 15,870
6 2020 var3 11,302
我尽量会用reshape2但它没有融化,t工作。它返回:
Var1 Var2 value NA NA NA
1 1 Year 2021 19,080 15,918 11,502
2 2 Year 2020 19,367 15,870 11,302
3 1 var1 2021 19,080 15,918 11,502
4 2 var1 2020 19,367 15,870 11,302
5 1 var2 2021 19,080 15,918 11,502
6 2 var2 2020 19,367 15,870 11,302
7 1 var3 2021 19,080 15,918 11,502
8 2 var3 2020 19,367 15,870 11,302
我做错了什么?
您可以使用以下代码:
df <- read.table(text=" Year var1 var2 var3
1 2021 19,080 15,918 11,502
2 2020 19,367 15,870 11,302", header = TRUE)
library(reshape2)
melt(df, id.vars = c("Year"), variable.name="Var")
#> Year Var value
#> 1 2021 var1 19,080
#> 2 2020 var1 19,367
#> 3 2021 var2 15,918
#> 4 2020 var2 15,870
#> 5 2021 var3 11,502
#> 6 2020 var3 11,302
由reprex包(v2.0.1)创建于2022-07-04