aju_k aju_k - 1 year ago 75
R Question

specifying conditions as a variable to assign values in R

I have a dataframe to which I would like to assign percentages and reasons based on conditions:

df$profile[ColumnX>=0.5, ColumnY == 2]<-"Profile 1"
df$prediction[ColumnX>=0.5, ColumnY == 2]<-0.84
df$reason[ColumnX>=0.5, ColumnY == 2]<-"Reason 1"

Can I avoid the duplication by using a variable for "ColumnX>=0.5, ColumnY == 2"?

I tried the following, but it is not working:

var <- expression(ColumnX>=0.5, ColumnY == 2)
df$profile[eval(var)]<-"Profile 1"
df$reason[eval(var)]<-"Reason 1"

Any help would be appreciated.

Answer Source

You could create a logical vector with your condition, and then subset based on this.

# sample data
df <- data.frame(X=runif(100), Y=sample(1:4, 100, replace = TRUE))

# create a logical vector with the conditions
var <- df$X >= 0.5 & df$Y == 2

# assign new values
df$profile[var] <- "Profile1"
df$prediction[var] <- 0.84
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download