簡體   English   中英

R 中數據框每一列的第 25 個分位數

[英]25th quantile for each column of a data frame in R

我正在嘗試遍歷 R 中的數據框。對於每一列,我想打印第 25 個分位數。

使用來自 nycflights13 包的數據,我正在嘗試以下操作:

abt <- select(flights, sched_dep_time)

for(i in names(abt)) {
  qrt_1 <- quantile(abt[i], c(.25))
  print(qrt_1)
}

但是,這給了我錯誤:錯誤: Must use a vector in [ 中Must use a vector in , not an object of class matrix.

我哪里走錯了?

這可能不會為您的問題提供解決方案,為什么它不起作用,但我想向您lapply()的替代方案

lapply(mtcars, function (x) quantile(x, 0.25))

這還會返回數據框中每列的 25% 分位數。 但是每一列都必須是數字(您在示例中假設)。

如果您想要矢量化輸出,您也可以使用sapply而不是lapply

在您的示例中,您使用select從“航班”數據框中選擇一列,該列返回一個帶有單列的tibble ,給出預定的起飛時間。 您沒有迭代數據框。

如果要遍歷航班數據框,則需要執行以下操作:

cat("25th Quantiles:\n===============\n")

for(i in names(flights)) 
{ 
  if(is.numeric(flights[[i]])) 
  {
    qrt_1 <- quantile(flights[[i]], c(.25), na.rm = TRUE)
    cat(i, ":", qrt_1, "\n")
  }
}

它將以下內容打印到控制台:

#> 25th Quantiles:
#> ===============
#> year : 2013 
#> month : 4 
#> day : 8 
#> dep_time : 907 
#> sched_dep_time : 906 
#> dep_delay : -5 
#> arr_time : 1104 
#> sched_arr_time : 1124 
#> arr_delay : -17 
#> flight : 553 
#> air_time : 82 
#> distance : 502 
#> hour : 9 
#> minute : 8 

可以通過管道與dplyr的summarise_if (@ emilliman5的評論):

library(tidyverse)

flights %>% 
  summarise_if(is.numeric, quantile, 0.25) 

由於您沒有提供任何可重現的示例,您可以檢查iris數據:


使用summarise_if

iris %>% 
   summarise_if(is.numeric, quantile, 0.25)

#  Sepal.Length Sepal.Width Petal.Length Petal.Width
#1          5.1         2.8          1.6         0.3     

或使用sapplyselect_if (原始答案):

iris %>% 
  select_if(is.numeric) %>% 
  sapply(quantile, 0.25)

#Sepal.Length.25%  Sepal.Width.25% Petal.Length.25%  Petal.Width.25% 
#             5.1              2.8              1.6              0.3 

暫無
暫無

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

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