Reputation: 191
I am trying to add a field in dataframe using the values in other columns depending on the condition in another column.
df <- data.frame(condition= c("startBin>7 & startBin<=12 & endBin>25 & endBin<=30","(startBin<=7 | startBin>12) & (endBin<=25 | endBin>30)","(startBin>7 & startBin<=12) & (endBin<=25 | endBin>30)","(startBin<=7 | startBin>12) & endBin>25 & endBin<=30"),
startBin = c(1,1,1,1), endBin = c(26,26,26,26), exprTemp=c("One","Two","Three","Four"))
I want to create a column "check" with value = 1 if the condition in "condition" column is satisfied. Thus, I want the updated dataframe as:
df <- data.frame(condition= c("startBin>7 & startBin<=12 & endBin>25 & endBin<=30","(startBin<=7 | startBin>12) & (endBin<=25 | endBin>30)","(startBin>7 & startBin<=12) & (endBin<=25 | endBin>30)","(startBin<=7 | startBin>12) & endBin>25 & endBin<=30"),
startBin = c(1,1,1,1), endBin = c(26,26,26,26), exprTemp=c("One","Two","Three","Four"), check=c(0,0,0,1))
Note that the value of check is 1 for the last record for which the condition is true.
I tried the following:
df$check <- eval(parse(text=paste0("ifelse(",df$condition,",1, '')",sep="")),df)
but it returned check = 1 for all rows as eval evaluates only the last condition.
Upvotes: 1
Views: 205
Reputation: 6147
Please try this code :
df <- data.frame(startBin = c(1,1,1,1), endBin = c(26,26,26,26), exprTemp=c("One","Two","Three","Four"))
condition= c("startBin>7 & startBin<=12 & endBin>25 & endBin<=30","(startBin<=7 | startBin>12) & (endBin<=25 | endBin>30)","(startBin>7 & startBin<=12) & (endBin<=25 | endBin>30)","(startBin<=7 | startBin>12) & endBin>25 & endBin<=30")
parsedcond=(parse(text = condition))
newcol=logical(nrow(df))
for(i in 1:nrow(df))
newcol[i] <- with(df, eval(parsedcond[i]))[i]
df <- data.frame(df, newcol)
> df
startBin endBin exprTemp newcol
1 1 26 One FALSE
2 1 26 Two FALSE
3 1 26 Three FALSE
4 1 26 Four TRUE
Upvotes: 1