R:转换数据,如Excel Pivot table

R: Transform data, like Excel Pivot table

我正在努力将我的数据转换为以下输出。输出值是count的总和。

怀疑这将涉及 group_by()pivot_wider()summarise(),但运气不好。

数据:

df1 <- rbind(animal.boolean = c("Y","Y","Y","Y","Y","Y","N"),
             animal.detailed = c("cat", "mouse", "dog", "mouse", "cat", "dog", "cupboard"), 
             count = c(2,1,4,1,8,1,1))

输出:

df2 <- rbind(c(10,2,5,0), c(0,0,0,1))
colnames(df) <- c("cat", "mouse", "dog", "cupboard")
rownames(df) <- c("Y","N")

那个矩阵是非常糟糕的输入格式。我们可以转置它并将其转换为数据框,然后使用 pivot_widervalue_fn 参数来跳过单独的 group_by() %>% summarize() 步骤。

library(tidyr)
library(readr)
t(df1) %>%
  as.data.frame() %>%
  type_convert() %>%
  pivot_wider(
    names_from = animal.detailed,
    values_from = count,
    values_fill = 0,
    values_fn = sum
)
# # A tibble: 2 × 5
#   animal.boolean   cat cupboard   dog mouse
#   <chr>          <dbl>    <dbl> <dbl> <dbl>
# 1 Y                 10        0     5     2
# 2 N                  0        1     0     0