How should I use nested ifelse statements?
We need to use %in%
instead of ==
:
rock$status <- ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") &
rock$sex != "F", "1F",
ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") &
rock$sex == "F", "Female",
ifelse(rock$name %in% c("A", "B", "C", "D") &
rock$age > 15, "Young", "Others")))
rock
# name age sex status
# 1 A 22 M Young
# 2 B 43 F Young
# 3 C 12 M Others
# 4 D 17 M Young
# 5 E 29 M 1F
# 6 F 5 F Female
# 7 G 51 F Female
# 8 H 56 M 1F
# 9 I 9 F Female
# 10 J 44 F Female
nested ifelse in R
Normal scenario works for me.
disc_freq <- c("1.Low_disc", "2.Med_disc", "3.High_disc", "4.na")
promo_freq <- c("1.Low_promo", "3.High_promo", "3.High_promo", "4.na")
Promotion1 <- data.frame(disc_freq, promo_freq)
Promotion1
disc_freq promo_freq
<fctr> <fctr>
1.Low_disc 1.Low_promo
2.Med_disc 3.High_promo
3.High_disc 3.High_promo
4.na 4.na
Promotion1$promo_segmnt <-
ifelse(
(Promotion1$disc_freq == "1.Low_disc") &
(Promotion1$promo_freq == "1.Low_promo"),
"1.Low",
ifelse(
(Promotion1$disc_freq == "2.Med_disc") &
(Promotion1$promo_freq == "3.High_promo"),
"3.High",
ifelse(
(Promotion1$disc_freq == "3.High_disc") &
(Promotion1$promo_freq == "3.High_promo"),
"3.High ",
"NA"
)
)
)
[1] "1.Low" "3.High" "3.High " "NA"
It is possible there are some extra spaces in your columns. you can remove it using stringr package.
library(stringr)
Promotion1 $disc_freq<- str_trim(Promotion1 $disc_freq, side = "both")
Promotion1 $promo_freq<- str_trim(Promotion1 $promo_freq, side = "both")
then try ifelse again.
syntax for nested ifelse and if statements in R
We can use a group by approach - grouped by 'Date', 'Location', subset the 'pH' where 'Code' value is "F" (assuming only a single "F" per Location) and then subtract from the 'pH' column
library(dplyr)
df1 <- df1 %>%
group_by(Date, Location) %>%
mutate(phDelta = pH - pH[Code == "F"][1]) %>%
ungroup
Way to avoid nested ifelse statement in R
Following @Claudiu Papasteri recommendations:
Package
library(dplyr)
Solution
df %>%
mutate(age_band = case_when( age %in% c("15 to 17","18 and 19") ~ '15 to 19',
age %in% c("20 to 24","25 to 29") ~ '20s',
age %in% c("30 to 34","35 to 39") ~ '30s',
TRUE ~'40+')
)
ps: I would include all specific statements in case_when
, even the last one for "40+", this way you can keep track of any problem in your dataset. Because if something is missing, or you have a typo, everything else will be coded as "40+". So by stating every case you can catch the problem and fix everything before running an analysis or generating graphs. And the last statement could be changed to TRUE ~ age
. This means, whatever remains, use the same value, or TRUE ~ NA
, that you recode the remaining stuff for missing. So you know that all missing means you have a problem you have to fix.
Output
age value age_band
1 15 to 17 1432 15 to 19
2 18 and 19 1112 15 to 19
3 20 to 24 1265 20s
4 25 to 29 1076 20s
5 30 to 34 1212 30s
6 35 to 39 1238 30s
7 40 to 44 1384 40+
8 45 to 49 1612 40+
9 50 to 54 1606 40+
10 55 to 59 1897 40+
Nested ifelse() statement in R not producing the desired results
Here is another possible option using rowSums
:
df$newvar <- +(rowSums(df, na.rm = TRUE) * NA ^ (rowSums(!is.na(df)) == 0) > 0)
# var1 var2 var3 newvar
#1 NA 1 NA 1
#2 NA NA NA NA
#3 NA 0 NA 0
#4 0 0 0 0
#5 1 1 1 1
Nested ifelse to output 3 responses in R
You could use cut
to create intervals and check, if a values falls into them:
library(dplyr)
df1 %>%
mutate(
check_1 = cut(time, breaks = df2$t_start, labels = FALSE),
check_2 = coalesce(cut(time, breaks = df2$t_end, labels = FALSE), 0),
check_3 = df2$control[check_1],
trial_type = case_when(
check_1 - check_2 == 1 & check_3 == 0 ~ "wt_int",
check_1 - check_2 == 1 & check_3 == 3 ~ "wt_control",
TRUE ~ "iti"
)
) %>%
select(-starts_with("check_"))
This returns
# A tibble: 7 x 6
initiate left right l_or_r time trial_type
<dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 0 0 1 1 2.82 iti
2 0 0 1 1 2.82 iti
3 0 0 1 1 2.82 iti
4 0 0 1 1 2.83 iti
5 1 0 0 0 16.8 wt_int
6 1 0 0 0 16.8 wt_int
7 1 0 0 0 187. wt_control
Data
df1 <- structure(list(initiate = c(0, 0, 0, 0, 1, 1, 1), left = c(0,
0, 0, 0, 0, 0, 0), right = c(1, 1, 1, 1, 0, 0, 0), l_or_r = c(1,
1, 1, 1, 0, 0, 0), time = c(2.8225, 2.82375, 2.825, 2.82625,
16.82, 16.8212, 187.08)), class = c("spec_tbl_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -7L), spec = structure(list(
cols = list(initiate = structure(list(), class = c("collector_double",
"collector")), left = structure(list(), class = c("collector_double",
"collector")), right = structure(list(), class = c("collector_double",
"collector")), l_or_r = structure(list(), class = c("collector_double",
"collector")), time = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
df2 <- structure(list(trial = c(1, 2, 3, 4, 11, 12, 30), control = c(0,
0, 0, 0, 3, 0, 3), t_start = c(16.64709, 41.81843, 65.5451, 82.65743,
187.0787, 200.0486, 415.171), t_end = c(35.49431, 57.74304, 71.16612,
87.30914, 193.5898, 203.1883, 418.0405)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -7L), spec = structure(list(
cols = list(trial = structure(list(), class = c("collector_double",
"collector")), control = structure(list(), class = c("collector_double",
"collector")), t_start = structure(list(), class = c("collector_double",
"collector")), t_end = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
How to avoid repeating the same 'else' statement in multiple nested if/else?
In the case of nested if else, you can use a guard
type statement. guard
is popular in case of nested if-else and provides a clean code.
Guard statement tries to element the else cases first. You know we write else cases to perform deviated paths. So what if we remove the
deviated paths first.
For example, if you have
if condition A == "Yes":
print("A")
if condition B == "Yes":
print("B")
else:
print("D")
if condition C =="Yes":
print("C")
else:
print("D")
else:
print("D")
Now I can formatting the following
// 1
if condiation A == "No" {
print("D")
return
}
// 2
if condition B == "Yes" {
print("B")
return
}
if condition C == "No" {
print("D")
return
}
print("C")
For more follow the link: - Youtube
Related Topics
Error in If/While (Condition) {: Missing Value Where True/False Needed
How to Select the Rows With Maximum Values in Each Group With Dplyr
What Specifically Are the Dangers of Eval(Parse(...))
Drop Data Frame Columns by Name
Convert a List to a Data Frame
Left Align Two Graph Edges (Ggplot)
Gather Multiple Sets of Columns
Linear Regression and Group by in R
Does Ifelse Really Calculate Both of Its Vectors Every Time? Is It Slow
How to Remove All Duplicates So That None Are Left in a Data Frame
How to Save a Plot as Image on the Disk
Add Count of Unique/Distinct Values by Group to the Original Data
Replace Missing Values (Na) With Most Recent Non-Na by Group
How to Specifically Order Ggplot2 X Axis Instead of Alphabetical Order
Show Percent % Instead of Counts in Charts of Categorical Variables
Error in Confusion Matrix:The Data and Reference Factors Must Have the Same Number of Levels