Gabrielle Macklin
Gabrielle Macklin

Reputation: 63

Dividing Counts only of certain groups

An example of data

Var1 <- rep(c("X", "Y", "Z"),2)
Var2 <- rep(c("A","B"),3)
Count<-sample(c(10:100), 6)
data<-data.frame(Var1,Var2,Count)

Produces

   Var1 Var2 Count
1    X    A    89
2    Y    B    97
3    Z    A    29
4    X    B    38
5    Y    A    50
6    Z    B    88

I would like to divide the counts only of Var2 B by two, to get

   Var1 Var2 Count Count2
1    X    A    89    89
2    Y    B    97    48.5
3    Z    A    29    29
4    X    B    38    19
5    Y    A    50    50
6    Z    B    88    44

But I'm not sure how to only divide based on a variable.

I'm new to coding, so any help is appreciated!

Upvotes: 0

Views: 177

Answers (3)

akrun
akrun

Reputation: 886978

With data.table

library(data.table)
setDT(data)[, Count := as.numeric(Count)][Var2 == 'B', Count := Count/2]

Upvotes: 0

J Thompson
J Thompson

Reputation: 164

Slight variation to Brian's dplyr solution, use replace to update a portion of the column inside the mutate function.

require(tidyverse)

Var1 <- rep(c("X", "Y", "Z"),2)
Var2 <- rep(c("A","B"),3)
Count<-sample(c(10:100), 6)
data<-data.frame(Var1,Var2,Count)

data %<>%
  mutate(Count=replace(Count, Var2=='B', Count[Var2=='B']/2))

Upvotes: 0

Brian Fisher
Brian Fisher

Reputation: 1367

Base R solution:

data$Count2 <- data$Count  ## copy to new variable
## Then change the subset to desired value. LHS subsets, RHS provides change
data$Count2[data$Var2 == "B"] <- data$Count[data$Var2 == "B"]/2

And Tidyverse/dplyr solution

library(dplyr)
data = data %>%
      mutate(Count2 = ifelse(Var2 == "B", Count/2, Count ))

# alternatively, this is identical to above
data = mutate(data, Count2 = ifelse(Var2 == "B", Count/2, Count ))

Upvotes: 1

Related Questions