0

我有一个示例数据集,如下所示

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

我想用零替换 p2 列中的 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和其他索引运算符,但我只是遇到了一堵砖墙。如果我能得到一个索引方法,那将是最好的,因为我的数据集很大。

4

1 回答 1

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
于 2012-11-26T14:44:15.150 回答