繁体   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