【发布时间】:2020-02-28 10:34:25
【问题描述】:
从下面的代码中,df 是一个包含 ID 和 Date 变量的数据框。 df1 是一个固定的数据框。我希望创建一个具有这些条件的新向量: 如果来自 df 的日期介于 df1 中的开始日期和结束日期之间,并且来自 df 的 ID 等于 df1 中的 ID1,则代码将从 df1 返回相应的结果。但是,我收到了这些警告消息,如下面的代码所示。请帮忙。
> Date = as.Date(c("01/01/2012", "01/02/2015", "01/01/2018", "01/05/2019"), format = '%d/%m/%Y')
> ID = c(1,2,3,1)
> df = data.frame(ID, Date)
>
> Start_Date = as.Date(c("01/01/2011", "01/01/2011", "01/01/2019"), format = '%d/%m/%Y')
> End_Date = as.Date(c("31/12/2018", "31/12/2019", "31/12/2019"), format = '%d/%m/%Y')
> ID1 = c(1,2,3)
> Result =c("A","B","C")
> df1 = data.frame(ID1,Start_Date,End_Date, Result)
>
> for(i in 1:nrow(df1)) {
+ if(Date >= Start_Date[i] & Date <= End_Date[i] & ID == ID1[i]) {Result[i]}
+ }
Warning messages:
1: In if (Date >= Start_Date[i] & Date <= End_Date[i] & ID == ID1[i]) { :
the condition has length > 1 and only the first element will be used
2: In if (Date >= Start_Date[i] & Date <= End_Date[i] & ID == ID1[i]) { :
the condition has length > 1 and only the first element will be used
3: In if (Date >= Start_Date[i] & Date <= End_Date[i] & ID == ID1[i]) { :
the condition has length > 1 and only the first element will be used
【问题讨论】:
标签: r