melanie chetry
melanie chetry

Reputation: 123

Finding a maximum value in a row using row name and reporting the found value and column name

I have a data frame which contains four countries and three variable x,y,z. Now I'm trying to create a function that returns the highest value of the defined row and the column name which contains the highest value in the row.

           x           y          z 
Sweden  1.6534561  0.11523404  0.2261730 
France -1.2274320 -0.24096054  1.5096028
England -1.4503096  0.07227427  1.6740867
Spain  0.1867416  1.25318913 -0.7350560 

The problem is I don't understand how I could use the row_name in finding the highest value in that row.

my_function(row_name){

value=
column=

paste("Highest value is", value, "and it is in column", column)
}

For example

my_function("Sweden") should return "Highest value is 1.6534561 and is in column x"

Upvotes: 0

Views: 117

Answers (3)

fabla
fabla

Reputation: 1816

I have created a simple dataset that is not identical but very similar to yours.

Data

df <- structure(list(x = 1:4, y = c(4, 8, 1, 6), z = c(3, 4, 1, 5)), class = "data.frame", row.names = c("Sweden", 
"France", "England", "Spain"))

The function utilizes basic indexing and requires you to additionally specify the data.frame, you can remove this feature if you wish.

Function

my_function <- function(Row, df){
 max <- max(df[Row, ])
 row <- which(df[Row, ] == max)
 paste("Highest value is", max, "and it is in column", names(df)[row])
}

> my_function("Sweden", df)
[1] "Highest value is 4 and it is in column y"

Upvotes: 1

NelsonGon
NelsonGon

Reputation: 13319

A tidyverse approach:

library(dplyr)
df %>% 
   mutate(ID= row.names(.)) %>% 
   tidyr::gather(key,val,-ID) %>% 
   group_by(ID) %>% 
   filter(val==max(val))
# A tibble: 4 x 3
# Groups:   ID [4]
  ID      key     val
  <chr>   <chr> <dbl>
1 Sweden  x      1.65
2 Spain   y      1.25
3 France  z      1.51
4 England z      1.67

To make a function(Note that this might require some non standard evaluation),

max_finder <- function(df, target_id){

   df %>% 
     mutate(ID= row.names(.)) %>% 
     tidyr::gather(key,val,-ID) %>% 
     group_by(ID) %>% 
     filter(val==max(val), ID ==target_id)

 }



max_finder(df,"Sweden")
# A tibble: 1 x 3
# Groups:   ID [1]
  ID     key     val
  <chr>  <chr> <dbl>
1 Sweden x      1.65

Data:

df<- structure(list(x = c(1.6534561, -1.227432, -1.4503096, 0.1867416
    ), y = c(0.11523404, -0.24096054, 0.07227427, 1.25318913), z = c(0.226173, 
    1.5096028, 1.6740867, -0.735056)), class = "data.frame", row.names = c("Sweden", 
    "France", "England", "Spain"))

Upvotes: 2

Lucas Pe&#241;alver
Lucas Pe&#241;alver

Reputation: 31

my_function(row_name){

value=max(dataframe["row_name", ])
for(i in c(1:length(a["row_name",])) {
if(a["row_name",i] == value
column=names(dataframe)[i]
}
paste("Highest value is", value, "and it is in column", column)
}

Upvotes: 1

Related Questions