Apply if else condition to make new column in r
We can use case_when like this:
library(tidyverse)
dat <- tibble(P.col = seq(0, 20000, 1000))
mutate(dat, P.bin = case_when(P.col >= 4000 ~ ">4000",
P.col <= 3000 & P.col >= 2000 ~ "2000-3000",
P.col <= 3000 & P.col >= 2000 ~ "2000-3000",
P.col <= 2000 & P.col >=1000 ~ "1000-2000",
P.col < 1000 ~ "1000"))
#> # A tibble: 21 x 2
#> P.col P.bin
#> <dbl> <chr>
#> 1 0 1000
#> 2 1000 1000-2000
#> 3 2000 2000-3000
#> 4 3000 2000-3000
#> 5 4000 >4000
#> 6 5000 >4000
#> 7 6000 >4000
#> 8 7000 >4000
#> 9 8000 >4000
#> 10 9000 >4000
#> # … with 11 more rows
Created on 2021-06-11 by the reprex package (v2.0.0)
Using If else to check multiple columns and create a new column based on the response for string responses
This is not the more efficient answer, neither the more general solution, but may satisfy a solution:
#create columns
st <- rep(NA,nrow(hairdf));
cur <- rep(NA,nrow(hairdf));
wav <- rep(NA,nrow(hairdf));
mix <- rep(NA,nrow(hairdf));
#join and define words
hairdf <- cbind(hairdf,st,cur,wav,mix);
words <- c("straight","curly","wavy","mixed");
words_ast <- paste(words,"*",sep=""); #just get the "*" words
#make a loop according to positions of columns st,cur,wav,mix
for (j in 1:length(words_ast)){ #let's see if we can evaluate 2 in words_ast
for (i in c(2,3,4)){ #but only in columns we selected
a <- subset(hairdf,hairdf[,i]==words_ast[j]) #subset columns which satisfay condition. [Note that this can be written as hairdf %>% subset(.[,i]==words_ast[j]) ]
hairdf[row.names(a),7+j] <- 2 #replace value from column 8
}
}
#repeat process for "words"
for (j in 1:length(words)){
for (i in c(2,3,4)){
a <- subset(hairdf,hairdf[,i]==words[j])
hairdf[row.names(a),7+j] <- 1
}
}
This should allow you to get the expected result. Alternatively, you can use the assign()
function, i.e
assign(x,value=1)
where x is each element in words.
So in a loop:
assign(words[n],value=1) ; assign(words_ast[n],value=2)
add new column to dataframe with if, else statement
I'm not sure about your data, but in your if-else if-else
statement, conditions like counties$Series_Complete >= 75
are now comparing whole vector with single value, and if using print
, it may not give you proper result. Instead, try using dplyr::case_when
library(dplyr)
counties %>%
mutate(class = case_when(
Series_Complete >=75 ~ 4,
Series_Complete >= 50 ~ 3,
Series_Complete >= 25 ~ 2,
TRUE ~ 1
))
Create new column in dataframe using if {} else {} in R
The if
statement is not suitable for this. You need to use ifelse
:
activityTimeAvgs$stepsImp <- ifelse(is.na(activityTimeAvgs$steps), activityTimeAvgs$avgsteps, activityTimeAvgs$steps)
Related Topics
What's the Difference Between Identical(X, Y) and Istrue(All.Equal(X, Y))
List of Word Frequencies Using R
Make R Exit with Non-Zero Status Code
Buffer (Geo)Spatial Points in R with Gbuffer
Edit Datatable in Shiny with Dropdown Selection for Factor Variables
How to Add Annotations Below the X Axis in Ggplot2
Heatmap-Like Plot, But for Categorical Variables
Pivot_Longer with Multiple Classes Causes Error ("No Common Type")
Time Series Plot Gets Offset by 2 Hours If Scale_X_Datetime Is Used
Efficiently Merging Two Data Frames on a Non-Trivial Criteria
Ggplot2, Geom_Bar, Dodge, Order of Bars
Create Binary Column (0/1) Based on Condition in Another Column
How to Properly Document S4 Methods Using Roxygen2
Create an R Package That Depends on Another R Package Located on Github
R: Apt-Get Install R-Cran-Foo VS. Install.Packages("Foo")
Rbind Error: "Names Do Not Match Previous Names"
Format Numbers to Significant Figures Nicely in R
Ggplot: Colour Points by Groups Based on User Defined Colours