Reputation: 21
I am confused about the conditional if statement in R.
What I want:
Let's say there are two variables; Data$Export & Data$Sales,
Only if both Data$Export & Data$Sales for a row has the value '0', I want the row to be removed from the dataset. Or, as I thought, to set any variable in the row to NA, which will consequently be removed with: "Data <- na.omit(Data) " anyway.
Therefore, I thought of the following construction:
for (i in 1:nrow(Data)) { if ( (Data$Sales[i] == 0) &(Data$Export[i] == 0 ) ) {Data$Sales [i] <- NA }}
Data <- na.omit(Data)
However, this does not work, the error code yields: missing value where TRUE/FALSE needed
Thank you in advance for any help I may receive.
Upvotes: 1
Views: 688
Reputation: 3502
I think you don't need to use conditional if statement to do so. Using diamonds
data.frame, you can remove rows that have 0 in both variables y
and z
as below. Thanks to @Moody, @Uwe and the OP comments, it should be | instead of &.
library(dplyr)
diamonds1 <- diamonds %>%
dplyr::filter(y!=0 | z!=0)
the same can be applied to your dataframe
data1 <- data %>%
dplyr::filter(Sales!=0 | Export!=0)
Upvotes: 0
Reputation: 47320
Data2 <- Data[Data$Export !=0 | Data$Sales != 0,]
Or to to set NAs
Data[Data$Export !=0 | Data$Sales != 0,] <- NA
Upvotes: 1