使用第一列作为变量名,反之亦然

Using the first column for variable names and vice versa with reshape

我有一个DF如下:

library(data.table)
DF <- structure(list(fullname = c(" Returns Count", " Dependent Exemptions Count", 
" Joint Returns Count", " Single Returns Count", " Head of Household Count"
), year = c(1998, 1998, 1998, 1998, 1998), State = c("Alabama", 
"Alabama", "Alabama", "Alabama", "Alabama"), Total_Returns = c(1879778, 
1354776, 774623, 690246, 382183), Breakeven_Loss = c(11649, 4254, 
5365, 5075, 591)), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"))

我想用行名切换第一列,同时保持州和年份不变。我尝试了多种方法,其中包括:

valvar <- names(DF)[4:16]
DF<- dcast(DF, year + State ~ fullname, value.var= valvar)

valvar <- names(DF)[4:16]
DF<- dcast(DF, year + State + valvar ~ fullname)

但都不起作用。我在这里错过了什么?

期望的输出:

先融化比较容易:

library(data.table)
DF[, melt(.SD, id.vars = c("year", "State", "fullname"))
   ][, dcast(.SD, variable + year + State ~ fullname)]

         variable year   State  Dependent Exemptions Count  Head of Household Count  Joint Returns Count  Returns Count  Single Returns Count
1:  Total_Returns 1998 Alabama                     1354776                   382183               774623        1879778                690246
2: Breakeven_Loss 1998 Alabama                        4254                      591                 5365          11649                  5075

首先以长格式获取数据,然后再次更改列名以宽格式获取数据。

library(tidyr)

DF %>%
  pivot_longer(cols = c(Total_Returns, Breakeven_Loss)) %>%
  pivot_wider(names_from = fullname, values_from = value)


# A tibble: 2 x 8
#   year State  name       ` Returns Count` ` Dependent Exemptions… ` Joint Returns Co… ` Single Returns C… ` Head of Household…
#  <dbl> <chr>  <chr>                 <dbl>                   <dbl>               <dbl>               <dbl>                <dbl>
#1  1998 Alaba… Total_Ret…          1879778                 1354776              774623              690246               382183
#2  1998 Alaba… Breakeven…            11649                    4254                5365                5075                  591