Search code examples
rfunctionselectcriteria

Extract a value from a dataframe iteratively (R)


I have a function to select a value from a dataframe. I want to select that value, save it, remove it from the dataset, and select a value using the same function from the remaining values in the dataframe. What is the best way to do this?

Here is a simple example:

V1 <- c(5,6,7,8,9,10)
df <- data.frame(V1)

V2 <- as.data.frame(matrix(nrow=3,ncol=1))

maximum <- function(x){
  max(x)
}

V2[i,]<- maximum(df)

df <- anti_join(df,V2,by='V1')

How can I set this up such that I reapply the maximum function to the remaining values in df and save these values in in V2?

I'm using a different and more complex set of functions and if/else statements than max - this is just an example. I do have to reapply the function to the remaining values, because I will be using the function on a new dataframe if df is empty.


Solution

  • Is this what you're looking for?

    V1 <- data.frame(origin = c(5,6,7,8,9,10))
    
    V2 <- as.data.frame(matrix(nrow=3,ncol=1))
    
    df1 <- V1
    df2 <- V2
    
    recursive_function <- function(df1,df2,depth = 3,count = 1){
      
      if (count == depth){
        # Find index
        indx <- which.max(df1[,1])
        curVal <- df1[indx,1]
        
        df2[count,1] <- curVal
        
        df1 <- df1[-indx, ,drop = FALSE]
        
        return(list(df1,
                    df2))
      } else {
        # Find index
        indx <- which.max(df1[,1])
        # Find Value
        curVal <- df1[indx,1]
        
        # Add value to new data frame
        df2[count,1] <- curVal
        
        # Subtract value from old dataframe
        df1 <- df1[-indx, ,drop = FALSE]
        
        recursive_function(df1,df2,depth,count + 1)
      }
    }
    
    recursive_function(df1,df2)