简体   繁体   English

使用数字条件替换特定组中的值

[英]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.如果“R”中的值> 0.2,我想搜索“R”列并将“R_event”列替换为“0”。 However, I would like to do this only for "Type 1" cells and not for the entire dataset.但是,我只想对“类型 1”单元格而不是整个数据集执行此操作。 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?关于如何解决此问题的任何建议?

First, I think you should convert your strings like "0.53" to numbers, 0.53.首先,我认为您应该将"0.53"类的字符串转换为数字0.53. This can be done with Table <- type.convert(Table) .这可以通过Table <- type.convert(Table)来完成。 Then, I like a direct replacement method:然后,我喜欢直接替换的方法:

# direct replacement
Table[Table$R > 0.2 & Table$Type == "Type 1", "R_event"] <- 0

I see you had a pipe attempt with %>% .我看到您尝试使用%>%进行 pipe 。 If you'd like to use dplyr for this, mutate is the main dplyr function for editing columns:如果您想为此使用dplyr ,则mutate是主要的dplyr function 用于编辑列:

library(dplyr)
Table <- Table %>%
  mutate(R_event = case_when(
    R > 0.2 & Type == "Type 1" ~ 0,
    TRUE ~ R_event   # in all other cases, leave R_event as-is
  ))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM