r语言 - if_else单独使用条件向量的每个元素



我正在编写一个R程序,该程序使用用户定义的函数来创建对象来清理/操作我们的原始数据。我对程序的要求之一是根据日期和一组 id 重新编码(有效切换(变量的某些部分。

set.seed(14)
date_switch2 <- as.POSIXct("2018-10-30")
maze_switch2 <- c(2,4)
test <-  data.frame(id = c(rep(1,4),rep(2,3), rep(3,8), rep(4,5)),
date = sort(rep(seq.Date(as.Date("2018-10-29"), as.Date("2018-11-01"),1),
each = 20), decreasing = F),
x = sort(x= round(runif(20,0, 10), 2), decreasing = F),
ant = sample(c("n", "s"), replace = T, size = 20))

使用此示例数据,我想重新编码/切换antdate == "2018-10-30"以进行id == c(2,4),以便n变得ss变得n。 询问程序的用户是否需要切换ant日期,如果是,则id哪个日期。这是使用

d <- readline(prompt = "Did antenna orientation change during study (y/n): ")
if(d == "y"){
date_switch2 <- readline(prompt = "On what date did antenna orientation change?: ")
maze_switch2 <- readline(prompt = "which mazes did antennae change orientation?: ")
}

我尝试使用if_else()但没有按预期工作,maze_switch2因为它包含两个元素,因此只有一半的时间正常工作。

if(d == "y") { 
test$ant2 <- dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch2 & as.character(test$ant) == "s", "n", 
dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch2 & as.character(test$ant)== "n", "s", 
as.character(test$ant)))  
} else {
test$ant2 <- test$ant
}

我想我可以使每个元素单独的对象。在此示例中,这将使此任务的代码量增加一倍,而不是通过用户定义的函数进行动态操作,也不会进行缩放。此解决方案需要动态且可扩展。我不知道用户会输入什么。

我最近的尝试是遍历maze_switch2;但它导致所有记录(即所有id(的NA>=感兴趣的日期。

if(d == "y") { 
for(i in maze_switch2) {
test$ant2 <- dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch[i] & as.character(test$ant) == "s", "n", 
dplyr::if_else(test$date >= switch & test$id == maze_switch[i] & as.character(test$ant)== "n", "s", 
as.character(test$ant)))  
}
} else {
test$ant2 <- test$ant
}

感谢您的帮助!

我想你非常接近。我只需要对您的代码进行最小的更改即可使其运行。

test <-  data.frame(id = c(rep(1,4),rep(2,3), rep(3,8), rep(4,5)),
date = sort(rep(seq.Date(as.Date("2018-10-29"), as.Date("2018-11-01"),1),
each = 20), decreasing = F),
x = sort(x= round(runif(20,0, 10), 2), decreasing = F),
ant = sample(c("n", "s"), replace = T, size = 20))

我用as.Date而不是as.POSIXct

d <- "y"
date_switch2 <- as.Date("2018-10-30")
maze_switch2 <- c(2,4)

我所做的唯一更改是在许多地方用%in%替换==,原因有两个:

1.to 测试d是否为"y"(我记得确切的原因,但我认为最好使用%in%测试字符"相同性"。但请随时纠正我...

2.tomaze_switch2测试多个值,test$id %in% maze_switch2

if(d %in% "y") { 
test$ant2 <- ifelse(test$date >= date_switch2 & test$id %in% maze_switch2 & as.character(test$ant) %in% "s", "n", 
ifelse(test$date >= date_switch2 & test$id %in% maze_switch2 & as.character(test$ant) %in% "n", "s", 
as.character(test$ant)))
} else {
test$ant2 <- test$ant
}

最新更新