Home > Software engineering >  R - Selecting the values of a column based on the values of another row
R - Selecting the values of a column based on the values of another row

Time:11-25

I have a dataframe df that looks like this

City          TreeID    Age   Diameter
City_1             X      1          6
City_1             Y      2          5 
City_2             Y      3          5 
City_3             X      4         10

I have a variable nominal that can be "TreeId", "Age" or Diameter and another variable city that has the name of a city stored in string format. I want to be able to pick up only the values of the column nominal for the correct city name

An example : city = "City_1" and nominal = "Age", then I should only pick up the values 1 and 2

I searched on here but nothing I could find was adapted to my case because I use variables so I don't know in advance which column I want to choose. I am lost, any help is appreciated. Thanks

CodePudding user response:

Here's a function to do that.

return_value <- function(data, city, nominal) {
  data[data$City == city, nominal]  
}

return_value(df, 'City_1', 'Age')
#[1] 1 2

return_value(df, 'City_2', 'Diameter')
#[1] 5

CodePudding user response:

You coul use pull:

library(dplyr)

df %>% 
  filter(City == "City_1") %>% 
  pull(Age)

df %>% 
  filter(City == "City_1") %>% 
  pull(Diameter)
[1] 1 2

[1] 6 5
  •  Tags:  
  • r
  • Related