locket
locket

Reputation: 761

R different calculations in dataframe based on row condition

I have the following dataframe df:

a<-c("Red","Red","Green","Red")
b<-c(1,1,1,1)
df<-data.frame(a,b)

I would like to +1 to b when the row of a is Red and -1 when it is Green. What's the best way of doing this?

Upvotes: 0

Views: 44

Answers (3)

AndrewGB
AndrewGB

Reputation: 16856

Here is a data.table option:

library(data.table)

setDT(df)[, b := fcase(a == "Red", b + 1,
                    a == "Green", b - 1, rep_len(TRUE, length(b)), b)]

Output

       a b
1:   Red 2
2:   Red 2
3: Green 0
4:   Red 2

Data

df <- structure(list(a = c("Red", "Red", "Green", "Red"), b = c(1, 
1, 1, 1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-4L))

Upvotes: 0

HoelR
HoelR

Reputation: 6563

library(tidyverse)

df <- tibble(
  a = c("Red","Red","Green","Red"), 
  b = c(1,1,1,1)
)

df %>%  
  mutate(b = case_when(a == "Red" ~ b + 1, 
                       a == "Green" ~ b - 1, 
                       TRUE ~ b))
#> # A tibble: 4 x 2
#>   a         b
#>   <chr> <dbl>
#> 1 Red       2
#> 2 Red       2
#> 3 Green     0
#> 4 Red       2

Created on 2022-07-03 by the reprex package (v2.0.1)

Upvotes: 1

akrun
akrun

Reputation: 887118

This can be done with a logical vector itself

df$b <- with(df, b + (a == "Red") - (a == 'Green'))

-output

> df
      a b
1   Red 2
2   Red 2
3 Green 0
4   Red 2

Or if there are only two unique values in 'a' column, use ifelse

df$b <- with(df, ifelse(a == 'Red', b + 1, b - 1))

data

df <- data.frame(a, b)

Upvotes: 2

Related Questions