2016-07-05 39 views
1

我想做一個函數來計算我可以應用於任何數據集的一些預先確定的彙總統計量度。我將以這裏的一個例子開始,但這是針對可能具有多種數據類型的數據集 - 例如字符,因子,數值,日期,包含空值等。R中的混合數據的摘要和描述表

我可以做到這一點很容易,如果數據全是數字 - 但處理IF應用,sapply等場景是我遇到語法問題的地方。 當它的所有數字我很好,因爲我可以做new_df = data.frame(min = sapply(mydf,2,min)..... etc ....等等)。當我在下面的示例中更復雜時,我無法獲得正確的語法。

在下面的例子我有3列的數據幀:

  • 所有數值
  • 數值用空
  • 分類編碼爲因子

I數據的列想要算出:

  • t YPE ...(字符,因子,日期,數字,等)
  • 的意思是......當數據類型是數字明顯,和不含零點
  • 數空值的數據集中

我覺得這是很簡單的,我可以用它從這裏跑..

副本,該代碼和名稱粘貼作爲數據幀的變量:

structure(list(allnumeric = c(10, 20, 30, 40), char_or_factor =  structure(c(2L, 
3L, 3L, 1L), .Label = c("bird", "cat", "dog"), class = "factor"), 
num_with_null = c(10, 100, NA, NA)), .Names = c("allnumeric", 
"char_or_factor", "num_with_null"), row.names = c(NA, -4L), class = "data.frame") 

預期溶液的數據幀(複製和分配給一個變量):

structure(list(allnumeric = structure(c(3L, 2L, 1L), .Label = c("0", 
    "25", "numeric"), class = "factor"), char_or_factor = structure(c(2L, 
    NA, 1L), .Label = c("0", "character"), class = "factor"), num_with_null =  structure(c(3L, 
    2L, 1L), .Label = c("2", "55", "numeric"), class = "factor")), .Names = c("allnumeric", 
    "char_or_factor", "num_with_null"), row.names = c("type", "mean", 
    "num_nulls"), class = "data.frame") 
+0

您的第二列的類型不應該是「factor」嗎? – akrun

回答

2

我們可以使用sapply遍歷的列,得到NA元件的classmean和數量,級聯(c(),並轉換爲data.frame

as.data.frame(sapply(df1, function(x) c(class(x), mean(x, na.rm=TRUE), 
           sum(is.na(x)))), stringsAsFactors=FALSE) 
+0

對不起 - 如果我然後想要總結值或採取分位數而不是使用均值?我在這裏收到有關因子/字符值的錯誤 – runningbirds

+0

@runningbirds如果它是'sum',則使用'sum(x,na.rm = TRUE)',而不是'mean(x,na.rm = TRUE)'。如果有因式/字符列使用if/else條件函數(x)c(class(x),if(is.numeric(x))mean(x,na.rm = TRUE)否則NA ,sum(is.na(x))))' – akrun