从长格式重塑为宽格式时,pivot_wider 会引入 NA 值

pom*_*mus 3 r tidyverse

当我使用 重塑数据时遇到问题pivot_wider()。

我的数据如下所示:

df <- data.frame(area = c( "Area1","Area1","Area1","Area2","Area2","Area2","Area3","Area3","Area3"),
                   species = c("species1","species2","species3","species1","species2","species3","species1","species2","species3"),
                   season= c("Season1","Season1","Season1","Season2","Season2","Season2","Season3","Season3","Season3"),
                   value= c(2,3,5,7,9,2,6,9,3))
Run Code Online (Sandbox Code Playgroud)

我可以将数据框更改为宽格式,如下所示。

df_wide <- df %>%
  mutate(row = row_number()) %>%
  pivot_wider(id_cols= c(row,species),
              ,names_from = "season",
              values_from = "value") %>%
  select(-row)
Run Code Online (Sandbox Code Playgroud)

这是输出的数字。

在此输入图像描述

我的问题是它引入了 NA,因为pivot_wider()为每个值创建一个新列。

在此输入图像描述

如果你帮助我,我会很棒...

sin*_*dur 5

library(tidyr)

pivot_wider(df, id_cols = species, names_from = season, values_from = value)

#   species  Season1 Season2 Season3
#   <chr>      <dbl>   <dbl>   <dbl>
# 1 species1       2       7       6
# 2 species2       3       9       9
# 3 species3       5       2       3
Run Code Online (Sandbox Code Playgroud)

或基数R:

cbind(species = unique(df$species), unstack(df, value ~ season))

#    species Season1 Season2 Season3
# 1 species1       2       7       6
# 2 species2       3       9       9
# 3 species3       5       2       3
Run Code Online (Sandbox Code Playgroud)