Matching and returning values based on condition or ID

Viewed 165

This seems like it should be fairly easy, but i'm having trouble with it.

Example: I have a dataframe with two columns IDs and perc_change. I want to know which unique IDs have had more than 30% change.

IDs <- c(1,1,2,1,1,2,2,2,3,2,3,4,5,6,3)
perc_change <- c(50,40,60,70,80,30,20,40,23,25,10,30,12,7,70)
df <- data.frame(IDs, perc_change)

So far:

if (df$perc_change > 30) {
unique(df$IDs)
} else {
}

This obviously doesn't work because it returns all unique IDs. Should I be be finding the index and then matching it or soemthing?

Thanks in advance!

4 Answers

We could do so, to get the values of each ID:

library(dplyr)

df %>% 
    group_by(IDs) %>% 
    filter(perc_change > 30) %>% 
    mutate(values = paste0(perc_change, collapse = ","), .keep="unused") %>% 
    distinct(IDs, .keep_all = TRUE)

Output:

    IDs values     
  <dbl> <chr>      
1     1 50,40,70,80
2     2 60,40      
3     3 70   

Just use [ to subset and take the unique - i.e. no need for if/else conditions

 with(df, unique(IDs[perc_change > 30]))
[1] 1 2 3

We can group, filter and count using dplyr

> library(dplyr)
> df %>% 
    group_by(IDs) %>% 
    filter(perc_change > 30) %>% 
    count(IDs)
# A tibble: 3 x 2
# Groups:   IDs [3]
    IDs     n
  <dbl> <int>
1     1     4
2     2     2
3     3     1
unique(df[df$perc_change > 30,"IDs"])
Related