Nick Knauer Nick Knauer - 1 day ago 5
R Question

Conditional Statement Not Working

I want to apply the following conditional statement:

"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."

I thought I had it right but it is only spitting out the date rather than the whole row.

Here is my sample code:

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


I tried this ifelse statement and to extract the row

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


It is giving me this result:

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


If True, I want this result:

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


If False, I want this result:

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

Answer

Try this instead:

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

ifelse is coercing subset(test, DAY == 1 ) to a list and only returning the first element because min(test$SysDay)==1 is a logical vector of length 1.

Comments