Conditional elseif statements in R
I have data that looks like this:
Animal
species sum
A 2
A 6
B 8
B 1
C 6
C 3
D 5
D 4
I need some code that divides the minimum amount by the maximum amount for each kind and creates a new column called ratio, and if that number is greater than .2, I want it to return that ratio, but if it is less than .2, I want it to be he returned NA. I would like to do it in dplyr This is the code I have but it doesn't work I have this command line in R
animal <- animal %>%
+ group_by(species) %>%
+ mutate(ratio = ifelse((min(sum)/max(sum) > .2), (min(sum)/max(sum)), "NA"))
Thank!
This is what the end should look like
species sum ratio
A 2 .333
A 6 .333
B 8 NA
B 1 NA
C 6 .5
C 3 .5
D 5 .8
D 4 .8
source to share
I would avoid ifelse
it because you have to evaluate the entire vector anyway, and because you need to calculate the whole process twice. This is how I would do it
library(data.table)
setDT(Animal)[, ratio := {r <- range(sum); r[1L]/r[2L]}, by = species]
Animal[ratio <= .2, ratio := NA]
# species sum ratio
# 1: A 2 0.3333333
# 2: A 6 0.3333333
# 3: B 8 NA
# 4: B 1 NA
# 5: C 6 0.5000000
# 6: C 3 0.5000000
# 7: D 5 0.8000000
# 8: D 4 0.8000000
source to share
You can use NA_real_
to make types compatible
animal %>%
group_by(species) %>%
mutate(ratio= ifelse((min(sum)/max(sum))> .2,
round((min(sum)/max(sum)),2), NA_real_))
# species sum ratio
#1 A 2 0.33
#2 A 6 0.33
#3 B 8 NA
#4 B 1 NA
#5 C 6 0.50
#6 C 3 0.50
#7 D 5 0.80
#8 D 4 0.80
The basic R option would be
animal$ratio <- with(animal, ave(sum, species, FUN=function(x) {
x1 <- min(x)/max(x)
NA^(x1 <= 0.2)*x1 }))
source to share
animal <- animal %>%
group_by(species) %>%
mutate(ratio = ifelse((min(sum)/max(sum) > .2), (min(sum)/max(sum)), as.numeric(NA)))
> animal
Source: local data frame [8 x 3]
Groups: species
species sum ratio
1 A 2 0.3333333
2 A 6 0.3333333
3 B 8 NA
4 B 1 NA
5 C 6 0.5000000
6 C 3 0.5000000
7 D 5 0.8000000
8 D 4 0.8000000
source to share