R 更改特定变量组的一列值

R 更改特定变量组的一列值,r,dplyr,R,Dplyr,我有以下数据集: help <- data.frame(id = c(rep(5, times = 5), rep(12, times = 3), rep(33, times = 2), rep(54, times = 3), rep(66, times = 4)), ob = c(rep(1, times = 5), rep(0, times = 3), rep(1, times = 2), rep(0, times =3), rep(1, time

我有以下数据集:

help <- data.frame(id = c(rep(5, times = 5), rep(12, times = 3), rep(33, times = 2), rep(54, times = 3), rep(66, times = 4)),
                   ob = c(rep(1, times = 5), rep(0, times = 3), rep(1, times = 2), rep(0, times =3), rep(1, times =4)))
我曾尝试:

change <- c(5, 66)
mutate(help, ob = ifelse(xor(id %in% change), ob == 0, 1))

change我们可以使用%
中的
%创建一个逻辑索引,然后根据该索引将'ob'的值分配给0

help$ob[help$id %in% c(5, 66)] <- 0

注:这两种方法都是
base R
方法

我们也可以通过
数据来实现。表
方法:

require(data.table)
setDT(help)
help[id %in% c(5, 66), ob := 0]
替换(帮助$ob,帮助$id%在%c(5,66),0中)
help$ob <- with(help, ifelse(id %in% c(5, 66), 0, ob))
require(data.table)
setDT(help)
help[id %in% c(5, 66), ob := 0]