runjumpfly runjumpfly - 13 days ago 5
R Question

Unusual output from ifelse using dplyr

I have a dataset K1 where I need to find whether the return is positive or not:
dput(K1)

structure(list(Date = structure(c(16892, 16895, 16896, 16897,
16898), class = "Date"), DailyRet = c(NA, -0.00120243315886267,
-0.0151193258267827, 0.0265683983462161, -0.00710933669538425
), Ticker = c("ABC.LTD", "ABC.LTD", "ABC.LTD", "ABC.LTD", "ABC.LTD"
)), .Names = c("Date", "DailyRet", "Ticker"), row.names = c(NA,
5L), class = "data.frame")


This is y attempt:

K2<-K1%>%group_by(Date)%>%
mutate(ret.sign =ifelse(DailyRet<0,"N","P"))


However,for date 2016-04-05 I get NA even though the DailyRet is negative and so sign should be N rather than NA.

dput(K2)
structure(list(Date = structure(c(16892, 16895, 16896, 16897,
16898), class = "Date"), DailyRet = c(NA, -0.00120243315886267,
-0.0151193258267827, 0.0265683983462161, -0.00710933669538425
), Ticker = c("ABC.LTD", "ABC.LTD", "ABC.LTD", "ABC.LTD", "ABC.LTD"
), ret.sign = c(NA, "N", NA, "P", "N")), .Names = c("Date", "DailyRet",
"Ticker", "ret.sign"), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -5L), vars = list(Date), labels = structure(list(
Date = structure(c(16892, 16895, 16896, 16897, 16898), class = "Date")), row.names = c(NA,
-5L), class = "data.frame", vars = list(Date), drop = TRUE, .Names = "Date"), indices = list(
0L, 1L, 2L, 3L, 4L))


Please help me understand why this is happening and how to solve it.

Answer

Just update dplyr and it should work fine.

Comments