将因子水平调整为列(不对值执行任何操作)

Reshape factor levels to columns (no action on values)

提问人:Nate 提问时间:11/16/2023 最后编辑:Nate 更新时间:11/16/2023 访问量:30

问:

我需要一些帮助来重塑我的数据帧。我只希望我的因子“季节”的每个级别成为 2 个新列,并且值来自“den”列(没有值的求和或平均值)。这可能是一项非常简单的任务,但我尝试的任何方法似乎都不起作用。

df %>%
      group_by(Season) %>%
      mutate(index = row_number()) %>%
      pivot_wider(names_from = "Season", values_from = "den")

Error in `n()`:
! Must only be used inside data-masking verbs like `mutate()`, `filter()`, and `group_by()`.
Run `rlang::last_trace()` to see where the error occurred.



spread(df, Season, den)

Error in `spread()`:
    ! Each row of output must be identified by a unique combination of keys.



reshape(data=df, timevar="Season",idvar="assem",direction="wide" )
                   assem   den.DRY   den.WET
1  Goldspotted Killifish 0.0000000 0.3333333
2                    Far 0.6666667 0.3333333
3                    Pal 0.0000000 1.3333333
4          Gulf Pipefish 0.0000000 0.0000000
18   Rainwater Killifish        NA 1.0000000
Warning messages:
1: In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  multiple rows match for Season=DRY: first taken
2: In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  multiple rows match for Season=WET: first taken

更新(我希望它采取的形式):

assem                   WET    DRY
Goldspotted Killifish   NA     0.000
Goldspotted Killifish   NA     0.000
Goldspotted Killifish   NA     0.000
Goldspotted Killifish   NA     0.000
Goldspotted Killifish   NA     1.333
Goldspotted Killifish   0.333  NA
Goldspotted Killifish   2      NA
Goldspotted Killifish   0.333  NA

数据:

structure(list(Season = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("DRY", 
"WET"), class = "factor"), assem = c("Goldspotted Killifish", 
"Far", "Pal", "Gulf Pipefish", "Pal", "Goldspotted Killifish", 
"Far", "Goldspotted Killifish", "Goldspotted Killifish", "Goldspotted Killifish", 
"Far", "Goldspotted Killifish", "Pal", "Gulf Pipefish", "Far", 
"Goldspotted Killifish", "Pal", "Rainwater Killifish", "Rainwater Killifish", 
"Goldspotted Killifish"), den = c(0, 0.666666666666667, 0, 0, 
0, 0, 0, 0, 1.33333333333333, 0, 0.333333333333333, 0.333333333333333, 
1.33333333333333, 0, 0, 2, 2.33333333333333, 1, 1.33333333333333, 
0.333333333333333)), row.names = c(NA, -20L), class = "data.frame")
r 重塑

评论


答: 暂无答案