我有一个样本数据集,如下所示
sampDate <- as.Date(c("2011-09-01","2011-09-02","2011-09-03","2011-09-04","2011-09-05", "2011-09-06"), format ="%Y-%m-%d")
p1 <- c( 10, 6.1, 11.1, 9.1, 10.1, 7)
p2 <- rep(1,6)
df <- data.frame(sampDate,p1,p2);df
sampDate p1 p2
1 2011-09-01 10.0 1
2 2011-09-02 6.1 1
3 2011-09-03 11.1 1
4 2011-09-04 9.1 1
5 2011-09-05 10.1 1
6 2011-09-06 7.0 1
我希望将第2列中的1替换为2011-09-01至2011-09-03,而不是零,以便生成的数据帧如下所示;
sampDate p1 p2
1 2011-09-01 10.0 0
2 2011-09-02 6.1 0
3 2011-09-03 11.1 0
4 2011-09-04 9.1 1
5 2011-09-05 10.1 1
6 2011-09-06 7.0 1
我一直在尝试使用ifelse
和其他索引操作符,但我只是碰到了一堵砖墙。如果我得到一个索引方法,那将是最好的,因为我的大数据集。
答案 0 :(得分:2)
within(df, p2 <- replace(p2, sampDate>="2011-09-01" & sampDate<="2011-09-03", 0))
会做到这一点。
sampDate p1 p2
1 2011-09-01 10.0 0
2 2011-09-02 6.1 0
3 2011-09-03 11.1 0
4 2011-09-04 9.1 1
5 2011-09-05 10.1 1
6 2011-09-06 7.0 1