Replacing values within a specific group using a numeric condition

I have a sample dataset and code which is as follows:

structure(list(Variable = c(NA, "Continuous", "Cell 1", " ",  " ", " ", NA, "Cell 2", NA, NA, NA, NA, "Cell 3", NA, NA, NA,  NA, "Cell 3", NA, NA, NA, NA), Type = c(NA, NA, "Type 1", "Type 2",  "Type 3", "Type 4", "Other", "Type 1", "Type 2", "Type 3", "Type 4",  "Other", "Type 1", "Type 2", "Type 3", "Type 4", "Other", "Type 1",  "Type 2", "Type 3", "Type 4", "Other"), R = c(NA, NA, "1", "  NA",  "0.23", "0.14", "0.4", "0.4", "  NA", "0.88", "0.32", "0.17",  "1", "  NA", "0.39", "0.24", "0.84", "0.27", "  NA", "0.5", "0.27",  "0.18"), R_event = c(NA, NA, "1", "  NA", "0.67", "0.32", "0.53",  "0.81", "  NA", "0.88", "0.32", "0.36", "1", "  NA", "0.67",  "0.32", "0.84", "0.81", "  NA", "0.67", "0.32", "0.36")), class = "data.frame", row.names = c(NA, 
-22L))

I would like to search the 'R' column and replace the 'R_event' column with "0" if the value in 'R' is > 0.2. However, I would like to do this only for "Type 1" cells and not for the entire dataset. Here is the code that I tried:

Table <- read.csv("~/Desktop/Table.csv", stringsAsFactors = , na.strings = c("N/A", ""))

pacman::p_load(pacman, party, rio, tidyverse) 

Table$Type == "Type 1" %>% Table$R_event[Table$R>=0.2] <- 0

But I received the following error:

Error in Table$Type == "Type 1" %>% Table$R_event[Table$R >= 0.2] <- 0 : 
  could not find function "==<-"

Any suggestions on how I can resolve this issue?

Here are two methods. One uses base R and the other uses the mutate() function from dplyr.

DF$R_event <- ifelse(DF$R >= 0.2 & DF$Type == "Type 1", 0, DF$R_event)

library(dplyr)
DF <- DF %>% mutate(R_event = ifelse(R >= 0.2 & Type == "Type 1", 0, R_event))

One of the problems with your code is that %>% should be used to pass the result from the left side to a function on the right side. You have a data frame on the right side.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.