簡體   English   中英

帶數據框的R統計函數故障

[英]R Statistical Function Failure with Data Frames

當對數據幀使用mean(),sd()等函數時,出現“參數不是數字或邏輯上的”錯誤。

我從兩個向量創建了一個簡單的框架來測試功能(即,將stat函數與數據框架一起使用)。

str()提供以下內容:

'data.frame':   195 obs. of  2 variables:
 $ Births  : num  10.2 35.3 46 12.9 11 ...
 $ Internet: num  78.9 5.9 19.1 57.2 88 ...

使用mean()函數:

mean(frame2, na.rm=TRUE)

得到:

警告消息:在mean.default(frame2,na.rm = TRUE)中:參數不是數字或邏輯:返回NA

我已經看過以前的建議,不要在數據幀中使用mean(),這很好,但不是重點。

我正在閱讀O'Reilly R Cookbook,它聲稱您應該能夠在數據幀中使用mean()和sd()。

但是,我無法使其工作。

關於您的問題:

我無權訪問您的書或其他學習資源,但最好的學習工具是R幫助。 因此,要理解參數的類型,您可以執行以下操作: ?mean ,它表示:

mean(x, trim = 0, na.rm = FALSE, ...)
Arguments

x   An R object. Currently there are methods for numeric/logical vectors and date, date-time and time interval objects. Complex vectors are allowed for trim = 0, only. 

因此,正如它所解釋的,它最適合vectors ,也基於這個問題 ,我認為您的書有些陳舊。 獲取您的R版本,並將其與book進行比較。


在此示例中,它對我來說效果很好:

dt<-data.frame(Births =sample(c(1:100),50),
           Internet =sample(c(1:100),50))

str(dt)
mean(dt$Births)

或者即使我將數據設為num仍然有效:

dt<-data.frame(Births =as.numeric( sample(c(1:100),50)),
           Internet =as.numeric(sample(c(1:100),50)))

str(dt)
mean(dt$Births)

如果您希望傳遞數據框並一次性獲得常規信息,則可以使用summary功能:

summary(iris)

有兩種選擇,第一種是在確實所有列都是數字的情況下起作用,第二種是匯總數字列:

dt %>% dplyr::summarise_all(mean)
dt %>% dplyr::summarise_if(is.numeric, mean)


  Births Internet
1  47.86    47.52

暫無
暫無

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

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