r - pivot_wider 在从长格式 reshape 为宽格式时引入 NA 值

标签 r tidyverse

<分区>

我在使用 pivot_wider() reshape 数据时遇到问题。

我的数据是这样的:

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))

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

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

这是输出图。

enter image description here

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

enter image description here

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

最佳答案

试试这个。您需要一个宽数据框,所以问题是行号和区域正在创建可能会扰乱预期输出的额外行。解决此问题的一种方法是:

library(dplyr)
library(tidyr)
#Code
newdf <- df %>% select(-area) %>% pivot_wider(names_from = season,values_from=value)

输出:

# A tibble: 3 x 4
  species  Season1 Season2 Season3
  <fct>      <dbl>   <dbl>   <dbl>
1 species1       2       7       6
2 species2       3       9       9
3 species3       5       2       3

关于r - pivot_wider 在从长格式 reshape 为宽格式时引入 NA 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64356531/

相关文章:

r - 使用 qqmath 或 dotplot : How to make it look fancy? 绘制来自 lmer(lme4 包)的随机效应

r - 将一组列与另一组列相乘的整洁方法

r - 如何使用 dplyr 分组进行统计测试,然后用扫帚制作 tibble

r -\Sexpr{} 在 .tex 文件中引用 R 对象

c - 是否有必要保护 .Call 参数?

仅删除换行符之间的空格

r - 浏览器刷新后交互式 rmarkdown 文档无法正确显示

r - 从数据框中的所有分类变量创建虚拟变量

r - 变异多个变量以创建多个新变量

r - 循环跨列相乘