'I want to replace dplyr style, but I don't know how to do it in R
I want to replace this code into dplyr style.
financials[is.na(ForecastEarningsPerShare), ForecastEarningsPerShare := ForecastEarningsPerShare2]
Could you tell me how to do it ?
Solution 1:[1]
From data.table:
financials[is.na(ForecastEarningsPerShare),
ForecastEarningsPerShare := ForecastEarningsPerShare2]
Into dplyr, perhaps literally:
financials %>%
mutate(
ForecastEarningsPerShare = if_else(is.na(ForecastEarningsPerShare),
ForecastEarningsPerShare2,
ForecastEarningsPerShare)
)
But a slightly easier-to-read method:
financials %>%
mutate(
ForecastEarningsPerShare = coalesce(ForecastEarningsPerShare,
ForecastEarningsPerShare2)
)
where coalesce uses the first non-NA value in the arguments and returns it (vectorized).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | r2evans |
