How to Assign a Value Using If-Else Conditions in R

How can I assign a value using if-else conditions in R

You can use ifelse to act on vectors with if statements.

ifelse(a>=10, "double", "single")

So your code could look like this

mydata <- cbind(a, ifelse(a>10, "double", "single"))

(Specified in comments below that if a=10, then "double")

using ifelse in data.table in R to assign values

You don't need ifelse here. (BTW there is fifelse from data.table.)

Try

library(data.table)
budget <- c(2000)

dt <- as.data.table(mtcars)[, .(cost = sum(hp)), by = gear]
dt[, costlimited := pmin(budget, cost)]
dt[, highCost := +(budget == costlimited)]
dt
# gear cost costlimited highCost
#1: 4 1074 1074 0
#2: 3 2642 2000 1
#3: 5 978 978 0

Assigning values from if-else blocks (how does it work?)

Let me focus on

What is bugging me is that I can't
work out why this code works—I was
amazed that it doesn't just throw an
error.

Why do you think so? What happens is that we have

  1. y being assigned an expression
  2. that expression being an if if() ...
  3. leading to either a TRUE or FALSE in the test
  4. leading to either one of the two branches being entered
  5. leading to the respective code being evaluated
  6. leading to its final value being the value of the right-hand-side
  7. leading to this value being assigned to y

Seems logical to me.

R If then do - how to create variables based on the condition

You don't need nested if commands.

if (test$year == 2018)
{
test$extra_var1 <- test$var1 + test$var2
test$extra_var2 <- test$var2 + test$var3
}

if (test$year == 2019)
{
test$extra_var1 <- test$var4 + test$var5
test$extra_var2 <- test$var5 + test$var6
}

which gives:

  year var1 var2 var3 var4 var5 var6 extra_var1 extra_var2
1 2018 1 3 5 7 9 11 4 8
2 2019 2 4 6 8 10 12 6 10

R if condition in row, assign value to new column - lappy/ifelse/for loop

Instead of nested if-elses, why not just two separate grep statements? Does this perform fast enough?

myData$tag <- NA 
myData$tag[grep("birthday", myData$URL)] <- "birthday"
myData$tag[grep("anni", myData$URL)] <- "anniversary"

Or, for a little flexibility and code-golf, collectively:

for (s in mytags) myData$tag[grepl(s,myData$URL)] <- s

Conditional assignment of value - is ifelse() the best when condition and intended return value don't have same features? [R]

We can use if/else instead of ifelse

alphabet <- if('B' %in% letters) letters else LETTERS


Related Topics



Leave a reply



Submit