【问题标题】:check constraints for each column by passing a row通过传递一行检查每一列的约束
【发布时间】:2019-10-04 12:42:26
【问题描述】:

对动态列数应用约束

我正在使用一个数据框,其中的列数可以是动态的。我想创建一个函数来检查数据的约束(主要是如果每个值都在最小值和最大值之间,如果给定的话)。我会将一些函数应用于将生成单行的行组合。我想将此行传递给约束函数并检查每列的值是否介于最小值和最大值之间。为此,我将给出一个约束矩阵,其列名与主数据框相同,第一行为最小值,第二行为最大值。有些列可能只有最小值或最大值。如果列是主数据框中的字符串,则最小值和最大值都将为 NA。不可用的值将是 NA。如果满足所有给定的约束,我希望函数返回 TRUE,否则返回 FALSE。如果传递的行的列多于约束矩阵(在数据操作期间生成的列),则只应检查约束矩阵中存在的列。我还希望该功能快速,并且我正在尝试使用应用系列功能,因为这种检查会发生很多次。

我尝试过 ifelse() 函数和逻辑运算符,但如果列数和约束是动态的,则无法应用。

# Function to Check Constraints
# df is a dataframe consisting of only one row on which constraints are to be checked
check_cons = function(df){
    df = c(df)
    return(ifelse( df$col1 > cons_col1_min, ifelse( df$col1 < cons_col1_max, ifelse( df$col2 > cons_col2_min, ifelse( df$col2 < cons_col2_max, ifelse( df$col3> cons_col3_min , ifelse( df$col3< cons_col3_max,T, F), F), F), F), F), F))    
}
# But this function cannot be used for dynamic number of constraints. 

我想要做的将类似于以下内容。

#Constraint Matrix
col1 col2 col3 col4 
4    7    NA   NA   
10   NA   17   NA

#I can have an input row like this
#Case 1:
col1 col2 col3 col4 
5    11    16   A   
# Passing this row should return values TRUE as it follows all the constraints
# col4 could have any max or min as both values not given and it is a character data
# col2 has a min constraint and col3 has a max constraint.

#Case 2:
col5 col1 col2 col3 col4
23   5    11    16   A  

# For this row constraints for col5 will not be checked as it is not given in the constraint matrix
# Positions of columns could be jumbled in the passed dataframe with one row
# This will also return the value as TRUE.

请告诉我您想到的任何类型的解决方案 一个近似的解决方案也会很有帮助。

【问题讨论】:

    标签: r dynamic apply check-constraints dynamic-columns


    【解决方案1】:
    check_cons<-function(inp,constr) { # allows you to define both the dataframe and the constraints
      constr<-constr[,!sapply(constr,function(x) all(is.na(x)))] # remove constraint columns that are all NA because they don't matter
      inp<-inp[,names(constr)] # remove columns that don't appear in the constraints matrix, and reorder the input according to the constraints
      all(inp>constr[1,], inp<constr[2,],na.rm=TRUE) # check the conditions
    }
    

    这是一个类似的解决方案,它采用多行的 data.frames,并使用 apply 检查每个帧的约束,输出 TRUE 和 FALSE 的向量:

    check_cons<-function(inp,constr) {
      constr<-constr[,!sapply(constr,function(x) all(is.na(x)))]
      inp<-inp[,names(constr)]
      suppressWarnings(apply(inp, 1, function(inp) all(inp>constr[1,], inp<constr[2,],na.rm=TRUE)))
    }
    

    (请注意,使用apply 将 data.frame 转换为矩阵,在这种情况下,如果任何列是字符类,则所有列都将变为字符。这就是为什么我从约束中删除了只有 NA 的列. 或者,您可以在上述apply 中的inp 参数之前使用“as.numeric”。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多