我有数据框,想要重新编码我可以比较未来实验的日期。但它不能用if语句重新编码日期。也许有提示这样做。
test <- data.frame(StartDate = c(rep("2015-02-16", 5), rep("2015-02-17", 5), rep("2015-02-23", 5), rep("2015-02-24", 5)),
response = sample(1:10,20,rep=TRUE)*7)
test$StartDate <- strptime(test$StartDate, format="%F")
test$day <- test$StartDate$mday
test$experimentday <- ifelse( (test$day == 16), 1, NA)
test$experimentday <- ifelse( (test$day == 17), 2, NA)
test$experimentday <- ifelse( (test$day == 23), 1, NA)
test$experimentday <- ifelse( (test$day == 24), 2, NA)
StartDate response day experimentday
1 2015-02-16 35 16 NA
2 2015-02-16 35 16 NA
3 2015-02-16 63 16 NA
4 2015-02-16 63 16 NA
5 2015-02-16 21 16 NA
6 2015-02-17 70 17 NA
7 2015-02-17 42 17 NA
8 2015-02-17 14 17 NA
9 2015-02-17 42 17 NA
10 2015-02-17 70 17 NA
11 2015-02-23 49 23 NA
12 2015-02-23 21 23 NA
13 2015-02-23 42 23 NA
14 2015-02-23 14 23 NA
15 2015-02-23 21 23 NA
16 2015-02-24 56 24 2
17 2015-02-24 42 24 2
18 2015-02-24 42 24 2
19 2015-02-24 21 24 2
20 2015-02-24 7 24 2
其他变体也不起作用
ifelse( test$day == 16, test$experimentday==1, test$experimentday==NA)
if(test$day == 16) {test$experimentday2 <- 1}
else {test$experimentday2 <- NA}
if(test$day == 16) test$experimentday3 <- 1
else test$experimentday3 <- NA
答案 0 :(得分:2)
您的代码正在按照您的说法进行操作。代码的最后一行,
test$experimentday <- ifelse( (test$day == 24), 2, NA)
如果experimentday
为24,则将day
的值设置为2,并将experimentday
的所有其他值设置为NA,从而有效地撤消前一行代码的工作。你可能想尝试这样的事情,而不是:
oldvalues <- c(16, 17, 23, 24)
newvalues <- c(1, 2, 1, 2)
test$experimentday <- newvalues[match(test$day, oldvalues)]