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

  • 本文关键字:数字 条件 替换 r
  • 更新时间 :
  • 英文 :


我有一个示例数据集和代码,如下所示:

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))

我想搜索"R"列并将"R_event"列替换为"R";0";如果"R"中的值>0.2。然而,我只想这样做是为了";类型1";单元格,而不是整个数据集。这是我尝试过的代码:

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

但我收到了以下错误:

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

关于如何解决这个问题,有什么建议吗?

首先,我认为应该将像"0.53"这样的字符串转换为数字,0.53.这可以用Table <- type.convert(Table)来完成。然后,我喜欢一种直接替换的方法:

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

我看到你用%>%做了一次管道尝试。如果您想使用dplyrmutate是用于编辑列的主要dplyr函数:

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
))

最新更新