简体   繁体   English

如何从过滤后的数据框中提取向量

[英]How can I extract vector from filtered data frame

How can I extract value from filtered data frame ?如何从过滤后的数据框中提取值?

For example let's take 100 hundred longest flights in flights data set.例如,让我们在航班数据集中取 10000 个最长的航班。

library(dplyr)
data(flights)<-data(flights) 
flights %>%
  slice_max(order_by=arr_time, n=100)

And I want to extract distance vector.我想提取距离向量。 So why I did is :所以我这样做的原因是:

df<-flights %>%
      slice_max(order_by=arr_time, n=100)

vec<-df['distance']

#Problem

length(vec)
150

So my question is : why the length is 150 and not 100 ?所以我的问题是:为什么长度是 150 而不是 100 ?

max value in arr_time is 2400 max在值arr_time是2400

max(flights$arr_time, na.rm = TRUE)
#[1] 2400

There are total 150 rows in flights which has that value. flights中共有 150 行具有该值。

sum(flights$arr_time == max(flights$arr_time, na.rm = TRUE), na.rm = TRUE)
#[1] 150

slice_max keeps all the rows in case of a tie hence all the rows are selected which has value 2400. If you want exact 100 rows arrange the data and then slice to select first 100 rows. slice_max保留所有行以防出现平局,因此所有行都被选中,其值为 2400。如果您想要精确的 100 行arrange数据,然后slice以选择前 100 行。

library(dplyr)
df %>% arrange(desc(arr_time)) %>% slice(1:100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM