我正在编写一个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))
使用此示例数据,我想在ant
上将date == "2018-10-30"
上的id == c(2,4)
重新编码/切换为n
变为s
,s
变为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。测试d是否为“ y”(我确切地记得为什么,但是我认为使用%in%
测试字符“相同”更好。但是随时可以纠正我...
2。用maze_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
}