user1566811
user1566811

Reputation:

Cut with different 'breaks' arguments for each value

I have a dataframe with a column of values on [0,1] (df$Estimate) and four columns (df$V1-4) of break values; each row is of the form c(0, [somevalue], 0.8, 1). For each value in df$Estimate, I want to pass its row's values of df$V1-4 to the cut function.

Code to replicate the example with a for-loop version of a solution:

nrow <- 10
set.seed(1)
df <- data.frame(Estimate = runif(nrow), V1 = 0, 
                 V2 = runif(nrow, 0.1, 0.75), 
                 V3 = 0.8, V4 = 1)
bins <- vector(length = nrow(df))
for (i in 1:nrow(df)) {
    bins[i] <- cut(df$Estimate[i], df[i, grep("V[0-9]", colnames(df))])
}

So I've got a kludgey solution, but what's the right way?

Upvotes: 0

Views: 125

Answers (2)

joran
joran

Reputation: 173517

Another apply solution using cut still:

 apply(df,1,function(x) cut(x[1],x[-1],labels = FALSE))

Upvotes: 0

juba
juba

Reputation: 49033

I don't know if it is the right way, but a possibility is to use findInterval :

apply(df, 1, function(v) { findInterval(v[1], v[2:5]) })

Upvotes: 2

Related Questions