条件语句不工作

Conditional Statement Not Working

我想应用以下条件语句:

"If the system day is 1, then extract the row in the dataframe containing a 1 in the DAY column, if it is not then just print out the full dataframe."

我以为我做对了,但它只是吐出日期而不是整行。

这是我的示例代码:

library(lubridate)
today <- Sys.Date()
day<-format(today, format="%d")
day <-as.numeric(day)
day

[1] 1

DATE <- as.Date(c('2016-10-31', '2016-11-01','2016-11-02','2016-11-03'))
Revenue <- c(1000,2000,3000,4000)
Count <- c(21000, 23400, 26800,5000)
Price<- c(5.00, 6.00, 6.75, 2.34)
df<-data.frame(DATE, Revenue, Count, Price)

df

        DATE Revenue Count Price
1 2016-10-31    1000 21000  5.00
2 2016-11-01    2000 23400  6.00
3 2016-11-02    3000 26800  6.75
4 2016-11-03    4000  5000  2.34    

df<-data.frame(DATE, Revenue, Count, Price)
df$DAY<-day(df$DATE)
test<-as.data.frame(df)
test$SysDay<-day  

        DATE Revenue Count Price DAY SysDay
1 2016-10-31    1000 21000  5.00  31      1
2 2016-11-01    2000 23400  6.00   1      1
3 2016-11-02    3000 26800  6.75   2      1
4 2016-11-03    4000  5000  2.34   3      1

我试过这个 ifelse 语句并提取行

ifelse(min(test$SysDay)==1, subset(test, DAY == 1 ), test)

它给我这个结果:

[[1]]
[1] "2016-11-01"    

如果为真,我想要这个结果:

        DATE Revenue Count Price DAY SysDay
2 2016-11-01    2000 23400     6   1      1 

如果为假,我想要这个结果:

        DATE Revenue Count Price DAY SysDay
1 2016-10-31    1000 21000  5.00  31      1
2 2016-11-01    2000 23400  6.00   1      1
3 2016-11-02    3000 26800  6.75   2      1
4 2016-11-03    4000  5000  2.34   3      1

试试这个:

if (min(test$SysDay)==1) { subset(test, DAY == 1 ) } else { test }

ifelsesubset(test, DAY == 1 ) 强制转换为 list 并且只返回第一个元素,因为 min(test$SysDay)==1 是长度为 1 的逻辑向量。