【问题标题】:Extract a value from a dataframe iteratively (R)迭代地从数据框中提取一个值 (R)
【发布时间】:2020-12-23 03:04:44
【问题描述】:

我有一个函数可以从数据框中选择一个值。我想选择那个值,保存它,从数据集中删除它,然后使用相同的函数从数据框中的剩余值中选择一个值。最好的方法是什么?

这是一个简单的例子:

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')

如何进行设置,以便将最大函数重新应用于 df 中的剩余值并将这些值保存在 V2 中?

我使用了一组不同且更复杂的函数和 if/else 语句,而不是 max - 这只是一个示例。我必须将函数重新应用于剩余值,因为如果 df 为空,我将在新数据帧上使用该函数。

【问题讨论】:

  • 我并没有在真正的函数中使用函数 max ——实际的函数太复杂了,无法在这里放上去。我最需要做的是知道如何使用函数从数据框中提取值,然后将相同的函数重新应用于没有该值的更新数据框。

标签: r function select criteria


【解决方案1】:

这是你要找的吗?

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)

【讨论】:

    【解决方案2】:

    这是我偶然发现的另一个解决方案:

    V1 <- c(5,6,7,8,9,10)
    df <- data.frame(V1)
    
    
    minFun <- function(df, maxRun){
      V2 <- as.data.frame(matrix(nrow=maxRun,ncol=1))
      for(i in 1:maxRun){
      V2[i,]<- min(df)
      df <- dplyr::anti_join(df,V2,by='V1')
      }
      return(V2)
    }
    
    test <- minFun(df = df, maxRun = 3)
    test
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2022-11-28
      • 2017-02-21
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多