[英]How to know the summary of the distance with ends_with selection
我試圖獲取與航班的距離的摘要以INC文本結尾
所以我確實加入了兩個數據庫來獲取名稱
flights <- left_join(flights, airlines, by="carrier")
比我使用的功能:
> flights %>% select(name, ends_with("Inc.")) %>% summarise(dist=sum(flights$distance))
# A tibble: 1 x 1
dist
<dbl>
1 350217607
並且還嘗試了:
> flights %>% filter(name, ends_with("Inc.")) %>% summarise(dist=sum(flights$distance))
Error: No tidyselect variables were registered
Call `rlang::last_error()` to see a backtrace
但在第一種情況下,其對所有航空公司的簡單總結而不是我指定的摘要應以“ Inc”結尾。 第二次審判只是說錯誤等...我在做什么錯?
謝謝
您可以通過多種方式進行操作,其中一些方法如下所示
library(dplyr)
flights %>% filter(grepl("Inc.$", name)) %>% summarise(dist = sum(distance))
# dist
# <dbl>
#1 249500641
flights %>% summarise(dist = sum(distance[grepl("Inc.$", name)]))
flights %>% slice(grep("Inc.$", name)) %>% summarise(dist = sum(distance))
或使用基數R
sum(with(flights, distance[endsWith(name, "Inc.")]))
#[1] 249500641
sum(with(flights, distance[grepl("Inc.$", name)]))
sum(with(flights, distance[grep("Inc.$", name)]))
另外請注意,不要在管道中經常使用$
,否則會弄亂計算。
我們可以使用tidyvverse
方法
library(dplyr)
library(stringr)
flights %>%
filter(str_detect(name, "Inc\\.$")) %>%
summarise(dist = sum(distance))
如果我們在select
語句中使用ends_with
,它將檢查列名稱並選擇匹配的列。 在這里,OP要選擇行。 因此,該模式應與所選列名上的filter
一起使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.