簡體   English   中英

在R中使用Sapply函數

[英]Using Sapply function in R

我想找到3列的最大值。 請在下面查看詳細信息,

  • 航班名稱列:AI,KF,AA
  • 國內價格欄:14.5、23.4、14.6
  • 國際價格欄:14.5、23.4、14.6
  • 往返列:44.34、35.78、31.24。

在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 == TRUEmax(x, na.rm =TRUE)

暫無
暫無

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

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