簡體   English   中英

dplyr()分組並獲取計數-錯誤消息評估錯誤:“ summarise_”的適用方法不適用於“邏輯”類的對象

[英]dplyr() grouping and getting counts - error message Evaluation error: no applicable method for 'summarise_' applied to an object of class “logical”

我有一個數據框(df),其中包含兩個變量,位置和天氣。

我想要一個寬數據框(dfgoal),其中將數據按位置分組,並在其中添加三個新變量(weather_1至weather_3),其中包含原始天氣變量中的觀測值。

問題是,當我嘗試使用dplyr():: mutate()時,我只會得到TRUE / FALSE輸出,而不是計數,或者是一條錯誤消息: Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical"

任何幫助將非常感激。

起點(df):

df <- data.frame(location=c("az","az","az","az","bi","bi","bi","ca","ca","ca","ca","ca"),weather=c(1,1,2,3,2,3,2,1,2,3,1,2))

預期結果(df):

dfgoal <- data.frame(location=c("az","bi","ca"),weather_1=c(2,0,2),weather_2=c(1,2,2),weather_3=c(1,1,1))

當前代碼:

library(dplyr)
df %>% group_by(location)  %>% mutate(weather_1 = (weather == 1)) %>% mutate(weather_2 = (weather == 2)) %>% mutate(weather_3 = (weather == 3))
df %>% group_by(location)  %>% mutate(weather_1 = summarise(weather == 1)) %>% mutate(weather_2 = summarise(weather == 2)) %>% mutate(weather_3 = summarise(weather == 3))

它非常簡單,具有稱為table的功能:

df %>% table  

        weather
location 1 2 3
      az 2 1 1
      bi 0 2 1
      ca 2 2 1

Krzysztof的解決方案是tidyverse的方法,但是如果您堅持使用tidyverse ,這是dplyr + tidyr的解決方案:

library(dplyr)
library(tidyr)

df %>%
  group_by(location, weather) %>%
  summarize(count = count(weather)) %>%
  spread(weather, count, sep="_") %>%
  mutate_all(funs(coalesce(., 0L)))

結果:

# A tibble: 3 x 4
# Groups:   location [3]
  location weather_1 weather_2 weather_3
    <fctr>     <int>     <int>     <int>
1       az         2         1         1
2       bi         0         2         1
3       ca         2         2         1

Krzysztof的答案出於簡單而取勝,但是如果您只希望使用tidyverse解決方案( dplyrtidyr ):

df %>% 
    group_by(location, weather) %>% 
    summarize(bin = sum(weather==weather)) %>%
    spread(weather, bin, fill = 0, sep='_')

結果是:

location    weather_1   weather_2   weather_3
az  2   1   1
bi  0   2   1
ca  2   2   1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM