[英]Using Sapply function in R
我想找到3列的最大值。 請在下面查看詳細信息,
在R中:
air <- data.frame(DomPrice = c(14.5, 23.4, 14.6),
IntPrice = c(14.5, 23.4, 14.6),
RoundTrip = c(44.34, 35.78, 31.24),
row.names = c("AI", "KF", "AA"))
我想找到使用R中的最高價格,國內價格,國際價格,往返價格的航班名稱。
表名稱/ csv文件名=空氣
你可以嘗試一個tidyverse
解決方案
library(tidyverse)
air %>%
rownames_to_column("flights") %>%
gather(k,v,-flights) %>%
group_by(k) %>%
mutate(M=ifelse(max(v)==v,T,F)) %>%
filter(M) %>%
select(-M)
# A tibble: 3 x 3
# Groups: k [3]
flights k v
<chr> <chr> <dbl>
1 KF DomPrice 23.4
2 KF IntPrice 23.4
3 AI RoundTrip 44.3
在R底下,您可以嘗試
data.frame(flight= row.names(air)[apply(air, 2, which.max)],
value = apply(air, 2, max))
flight value
DomPrice KF 23.40
IntPrice KF 23.40
RoundTrip AI 44.34
如果您對NA
na.rm == TRUE
則必須添加一個na.rm == TRUE
如max(x, na.rm =TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.