【问题标题】:Replacing values within a specific group using a numeric condition使用数字条件替换特定组中的值
【发布时间】:2021-04-29 13:29:11
【问题描述】:

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

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”中的值 > 0.2,我想搜索“R”列并将“R_event”列替换为“0”。但是,我只想对“类型 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 "==<-"

关于如何解决此问题的任何建议?

【问题讨论】:

    标签: r


    【解决方案1】:

    首先,我认为您应该将"0.53" 之类的字符串转换为数字0.53. 这可以通过Table &lt;- type.convert(Table) 完成。然后,我喜欢直接替换的方法:

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

    我看到您尝试使用 %&gt;% 进行管道传输。如果您想为此使用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
      ))
    

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 2016-06-20
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 2023-02-06
      相关资源
      最近更新 更多