If else statement with multiple conditions and 4 outcomes
I get "Occaisonal" using your code.
Your if statements are looking at logical vectors, but returning one value for ALL rows, for example:
df[,2]
is the whole column: 0.50 0.11 0.23 0.06 0.36 0.19
df[,2]>mean(relabund)
returns a logical vector of:
TRUE FALSE FALSE FALSE TRUE FALSE
by using &&
you are performing a logical comparison to two logical vectors. As these vectors aren't the same, you always get false:
df[,2]>mean(relabund) && df[,3]>mean(freq)
==
c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE) && c(FALSE, FALSE, TRUE, FALSE, TRUE, FALSE)
==
FALSE
Also, df$Classification
sets the column to be the same value, i.e. it's working on the whole dataset rather than row by row. What you need to do it perform vector operations on each row.
Using dplyr you can get an easier to read answer (for some!)
library(tidyverse)
species <- c("a", "b", "c", "d", "e", "f")
relabund <- c(.5, .11, .23, .06, .36, .19) #relative abundance
freq <- c(6, 3, 20, 2, 11, 4) #number of sites species occurs at
df = data.frame(species, relabund, freq)
df %>%
mutate(classify =
ifelse(freq < mean(freq) & relabund < mean(relabund),
"Rare",
ifelse(freq < mean(freq) & relabund > mean(relabund),
"Occaisonal",
ifelse(freq > mean(freq) & relabund < mean(relabund),
"Common",
ifelse(freq > mean(freq) & relabund > mean(relabund),
"Dominant",
"ERROR")))))
How to use ifelse in r with multiple conditions to change another variable to NA
The assignment should be outside the ifelse
df$RAIN <- ifelse(df$STATION==1 & df$YEAR==2001, NA, df$RAIN)
Also, instead of repeating thee 'df$', it would be much easier if we wrap inside with
df$RAIN <- with(df, ifelse(STATION == 1 & YEAR == 2001, NA, RAIN))
df
# STATION YEAR RAIN
#1 1 2000 5
#2 1 2001 NA
#3 1 2002 3
#4 2 2000 4
#5 2 2001 3
#6 2 2002 5
NOTE: In addition to the assignment, the &&
should be &
as the former returns only a single TRUE/FALSE as output. Also, data.frame(cbind
would mess up the types of columns as cbind
returns a matrix
first and matrix
can have only a single class.
NA
should not be quoted.
Regarding why only 5
is returned, as mentioned above the &&
returns a single TRUE/FALSE
df$STATION==1&&df$YEAR==2001
#[1] FALSE
In the ifelse
, now the no
part becomes active, and the first value for 'RAIN' is 5
ifelse(df$STATION==1&&df$YEAR==2001, NA,df$RAIN) # modified syntax related issues
#[1] 5
This gets assigned to the whole column
data
df <- data.frame(STATION,YEAR,RAIN)
How to make an ifelse statement with multiple conditions
The %in%
operator allows you to check against a vector of possible values.
game$homewin <- ifelse(game$outcome %in% c("home win OT",
"home win REG", "home win SO"), 1, 0)
You could also take advantage of the fact that TRUE
has a numerical representation of 1 and FALSE
of 0 and write:
game$homewin <- as.numeric(game$outcome %in% c("home win OT",
"home win REG", "home win SO"))
multiple ifelse with and and or conditions in R
I think by multiple ifelse you mean nested ifelse. if that is the case, here is a solution
df$bigcity <- ifelse(grepl("london|paris", df$location), ifelse(grepl("2011|2012", df$year), 1, 0), 0)
what I did here is, IF the first condition is true, place the second condition in TRUE parameter.
Using if else statement for multiple conditions
This can be done using either ifelse
with(dat, ifelse(x < 0.15 & dif <0, 3, ifelse(x > 0.15 & dif < 0, 2, 1)))
Or
with(dat, as.numeric(factor(1+4*(x < 0.15 & dif < 0) + 2*(x>=0.15 & dif < 0))))
R if statement with multiple conditions and multiple outcomes
Here's a simple approach using some math and logical vectors. This leverages the fact that + TRUE
evaluates to 1
.
First, make a character vector with the choices. Then Test if X1 is greater than the cutoff. That will equal 1
when TRUE
. Then test if X2 is greater than the cutoff and multiply by 2
. Then, add those two numbers together and add 1
. The total will equal 1
when neither, 2
when X1 is greater, 3
when X2 is greater, and 4
when both are.
Finally, subset your character vector using the integer vector you just created.
test$above <- c("neither","X1","X2","both")[((test$X1 > cutoff.X1) + ((test$X2 > cutoff.X2) * 2)) + 1]
head(test,10)
X1 X2 above
1 64 51 X1
2 39 31 X1
3 24 14 X1
4 74 57 X1
5 67 91 both
6 7 6 neither
7 14 78 X2
8 74 92 both
9 18 93 X2
10 27 31 X1
If you don't like that, there's always dplyr::case_when
, which is admittedly easier to read:
library(dplyr)
test$above <- case_when(test$X1 > cutoff.X1 & test$X2 > cutoff.X2 ~ "both",
test$X1 > cutoff.X1 ~ "X1",
test$X2 > cutoff.X2 ~ "X2",
TRUE ~ "neither")
Just remember that case_when
evaluates each condition until one evaluates TRUE
, so be sure to put the "both" condition first.
How to write ifelse statement with multiple conditions in R?
Use -
df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
df[is.na(df$result), "result"] <- "noresult"
df
Output
Team.1 Winner result
1 T1 T1 winner
2 T2 T1 loser
3 T2 <NA> noresult
4 T3 <NA> noresult
Calculation with multiple conditions in R DataFrame
Try
library(tidyverse)
df <- df %>% group_by(FundName) %>%
mutate(sum_Quantity = sum(Quantity),
mycol = ifelse(Quantity==0, abs(Value)/sum_Quantity, Value/Quantity))
Here you group by FundName and apply a simple mutate
command.
To sense-check, let's have a look at the rows/columns that are of interest:
df %>% filter(Quantity==0) %>% select(FundName, Quantity, NAVInitialDate, mycol)
# A tibble: 2 x 4
# Groups: FundName [2]
FundName Quantity NAVInitialDate mycol
<chr> <dbl> <dbl> <dbl>
1 SAFRA S&P SPECIAL FIC MULTIMERCADO 0 -Inf 540.
2 SAFRA CONSUMO AMERICANO FIC AÇÕES BDR NÍVEL I 0 -Inf 75.5
Related Topics
How to Add Row and Column to a Dataframe of Different Length
Splitting a Dataframe into Several Dataframes
Split an Audio File into Pieces of an Arbitrary Size
How to Fix Spaces in Column Names of a Data.Frame (Remove Spaces, Inject Dots)
Order Bars in Ggplot2 Bar Graph
Complete Dataframe With Missing Combinations of Values
Combine (Rbind) Data Frames and Create Column With Name of Original Data Frames
How to Convert Variable With Mixed Date Formats to One Format
Fitting a Linear Model With Multiple Lhs
Specify Custom Date Format For Colclasses Argument in Read.Table/Read.Csv
If Else Statements to Check If a String Contains a Substring in R
Multi-Row X-Axis Labels in Ggplot Line Chart
How to Keep Columns When Grouping/Summarizing
Removing Space Between Numeric Values in R
Transpose/Reshape Dataframe Without "Timevar" from Long to Wide Format
Annotating Text on Individual Facet in Ggplot2