Reputation: 53
I would like to find maximum value of 3 columns. Please see details below,
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
Upvotes: 0
Views: 128
Reputation: 17648
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)
Upvotes: 1