简体   繁体   中英

Using Sapply function in R

I would like to find maximum value of 3 columns. Please see details below,

  • Flights name column: AI, KF, AA
  • Domestic price column: 14.5, 23.4, 14.6
  • Internation price column: 14.5, 23.4, 14.6
  • round trip column: 44.34, 35.78, 31.24.

In 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"))

I want to find the names of the flights which have the maximum price, domestic price, international price, round trip using sapply in R.

Table name/csv file name = Air

You can try a tidyverse solution

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

In base R you can try

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

If you have trouble with NA 's you have to add a na.rm == TRUE like max(x, na.rm =TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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