0

I am trying to vectorize the following task with one of the apply functions, but in vain. I have a list and a dataframe. What I am trying to accomplish is to create subgroups in a dataframe using a lookup list.

The lookup list (which are basically percentile groups) looks like the following:

Look_Up_List
$`1`
   A   B     C     D     E
0.000 0.370 0.544 0.698 9.655 

$`2`
   A   B     C     D     E
0.000 0.506 0.649 0.774 1.192 

The Curret Dataframe looks like this :

Score Big_group
0.1     1
0.4     1 
0.3     2

Resulting dataframe must look like the following with an additional column. It matches the score in the percentile bucket from the lookup list in the corresponding Big_Group:

Score Big_group Sub_Group
0.1     1         A
0.4     1         B
0.3     2         A

Thanks so much

2
  • 2
    Awesome typo in header. Commented Jul 11, 2014 at 16:24
  • 1
    Would have been better to see "velcrotizing". Commented Jul 11, 2014 at 16:46

2 Answers 2

1

You can create a function like this:

myFun <- function(x) {
  names(Look_Up_List[[as.character(x[2])]])[
    findInterval(x[1], Look_Up_List[[as.character(x[2])]])]
}

And apply it by row with apply:

apply(mydf, 1, myFun)
# [1] "A" "B" "A"'
Sign up to request clarification or add additional context in comments.

Comments

0
   # reproducible input data
    Look_Up_List <- list('1' <- c(A=0.000, B=0.370, C=0.544, D=0.698, E=9.655),
                         '2' <- c(A=0.000, B=0.506, C=0.649, D=0.774, E=1.192))
    Current <- data.frame(Score=c(0.1, 0.4, 0.3),
                          Big_group=c(1,1,2))

    # Solution 1
    Current$Sub_Group <- sapply(1:nrow(Current), function(i) max(names(Look_Up_List[[1]][Current$Score[i] > Look_Up_List[[1]] ])))

    # Alternative solution (using findInterval, slightly slower at least for this dataset)
    Current$Sub_Group <- sapply(1:nrow(Current), function(i) names(Look_Up_List[[1]])[findInterval(Current$Score[i], Look_Up_List[[1]])])

    # show result
    Current

1 Comment

Current$Sub_Group <- sapply(1:nrow(Current), function(i) max(names(Look_Up_List[[1]][Current$Score[i] > Look_Up_List[[1]] ]))), but this only looks up Look_Up_List[[1]], as opposed to looking up Look_Up_List[[Big_group]]