簡體   English   中英

在 dataframe 中替換 psych::describe 的均值模式

[英]Replacing mean from psych::describe for mode in dataframe

我喜歡 psych::describe 的匯總統計數據,但我想用模式替換均值,但僅限於因子變量。 我如何對 Mode 的 output 進行編程以替換 setosa(或任何其他因子變量) 我使用 iris 進行復制,即使它只有一個。

getMode <- function(df) {
  ux <- na.omit(unique(df))
  ux[which.max(tabulate(match(df, ux)))]
}

Mode <- apply(iris%>% select(where(is.factor)), 2, getMode)

#I only want 5 of psych's descriptive stats plus the mode.
table <- cbind(psych::describe(iris),
                      Mode) [,c(3,4,8,9,2, 14)] 
table

我怎樣才能根據變量的結構來組合均值和眾數?

  1. 有沒有辦法將if_else與 where to tell R 當FALSE時做什么? 如果我能在變量不是一個因子時得到 output 的平均值,我會得到一個結合了平均值和模式的列。

Psych生成 dataframe,其中標識變量名稱不可選擇,因此這使得任何手動編碼或列出 mutate() 中的變量變得不可能。 它們也是我數據集中的大多數變量(因此即使可以完成,手動或 mutate(case_when) 也會非常乏味)。

附言。 我嘗試將我的apply()更改為map函數,但 output 與cbind()不兼容,因為它會列出每個因素的其他級別。 如果您對那部分代碼有更好的了解,或者認為那是我可以組合getModemean()的地方,我不介意建議。

如果您願意使用不同的 function 來生成相同類型的 output,則可以使用dplyrtidyr來完成此操作。 使用這種方法,您可以使用ifelse()做您想做的事情來識別數字或非數字變量。 唯一需要注意的是,如果您讓 function 為因子生成非數字值,則數字變量的 output 也必須是一個字符。 這就是為什么我將mean() function 包裝在sprintf()中。

getMode <- function(df) {
  ux <- na.omit(unique(df))
  ux[which.max(tabulate(match(df, ux)))]
}

library(tidyr)
iris %>% 
  summarise_all(.funs = list(
    mean = function(x)ifelse(is.numeric(x), sprintf("%.3f", mean(x)), as.character(getMode(x))), 
    sd = function(x)ifelse(is.numeric(x), sd(x), sd(as.numeric(x))), 
    min = function(x)ifelse(is.numeric(x), sprintf("%.3f", min(x)), levels(x)[1]), 
    max = function(x)ifelse(is.numeric(x), sprintf("%.3f", max(x)), levels(x)[length(levels(x))]), 
    n = function(x)sum(!is.na(x))
  )) %>% 
  pivot_longer(everything(),
        names_to = c("set", ".value"),
        names_pattern = "(.+)_(.+)")
                            
# A tibble: 5 x 6
#            set  mean     sd   min    max         n
#          <chr> <chr>  <dbl> <chr>  <chr>     <int>
# 1 Sepal.Length 5.843  0.828 4.300  7.900       150
# 2 Sepal.Width  3.057  0.436 2.000  4.400       150
# 3 Petal.Length 3.758  1.77  1.000  6.900       150
# 4 Petal.Width  1.199  0.762 0.100  2.500       150
# 5 Species      setosa 0.819 setosa virginica   150    
#     

這也允許您進行其他更改 - 例如上面,我用第一級Species替換了最小值,用最后一級Species替換了最大值。 並不是說這一定是您想要做的,但是很容易根據變量的類型更改 output 的值。

暫無
暫無

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

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