【问题标题】:Casting dataframe gives error R转换数据帧会产生错误 R
【发布时间】:2017-10-11 13:32:16
【问题描述】:

这是我尝试使用 cast 函数对其进行透视的数据框 df

dput(df)
structure(list(Val = c(1L, 2L, 2L, 5L, 2L, 5L), `Perm  1` = structure(c(1L, 
2L, 3L, 3L, 3L, 3L), .Label = c("Blue", "green", "yellow"
), class = "factor"), `Perm  2` = structure(c(1L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Blue", "green", "yellow"), class = "factor"), 
    `Perm  3` = structure(c(1L, 2L, 2L, 2L, 3L, 3L), .Label = c("Blue", 
    "green", "yellow"), class = "factor")), .Names = c("Val", 
"Perm  1", "Perm  2", "Perm  3"), row.names = c(NA, 6L), class = "data.frame")

并期待数据透视后的数据

Blue       1    1    1
green      2    4    9
yellow     14   12   7

我试过了

cast(df, df$Val ~ df$`Perm  1`+df$`Perm  2`+df$`Perm  3`, sum, value = 'Val')

但这会出错

Error: Casting formula contains variables not found in molten data: df$Val, df$`Perm1`, df$`Perm2`

我怎样才能进行枢轴,以便我能够获得所需的 O/P

P.S- 数据框 DF 大约有 36 列,但为简单起见,我只取了 3 列。 任何建议将不胜感激。

谢谢

多尼克

【问题讨论】:

    标签: r dataframe pivot reshape


    【解决方案1】:

    您似乎想要求和,按数据集中的每个排列分组。虽然 hacky,但我认为这适用于您的问题。首先,我们创建一个函数来使用 tidyeval 语法执行该求和。更多信息链接:Group by multiple columns in dplyr, using string vector input

    sum_f <- function(col, df) {
        library(tidyverse)
        df <- df %>% 
              group_by_at(col) %>% 
              summarise(Val = sum(Val)) %>% 
              ungroup()
        df[,2]
    }
    

    然后,我们使用 lapply 将其应用于您的数据集,并将总和绑定在一起。

    bind_cols(lapply(c('Perm1', 'Perm2', 'Perm3'), sum_f, df))
    

    这让我们得到了上述答案。 警告:需要知道你必须总结的列的名称才能工作。此外,每列需要具有相同级别的排列,即蓝色、绿色、黄色。代码将遵守此顺序。

    【讨论】:

    • 这对我很有效,非常感谢@jacobsg
    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 2016-09-27
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多