此问题源自此处给出的问题和答案: How to build a custom function that uses externally defined values with a string condition in R
有关将两个方程组合作为参数的评论使我感到好奇,并提出了以下两个问题:
1)如何基于将添加到eq_df的另一个字符串值(分组变量)使用多个方程式? (预期结果:data_df $ iso_value_p中每个单元格的长度不同的数值向量)
2)如果我也将此分组变量存储到data_df中,怎么可能调用一个方程(或多个)与eq_df中的该分组变量匹配的方程式? 代码如下:
#create dataframe with equation parameters
equation_id <- c("eq_1", "eq_2", "eq_3", "eq_4", "eq_5")
slope <- c(1.1627907, 1.6949153, 1.2658228, 0.9345794, 0.9433962)
intercept <- c(-26.4069767, -0.4067797, -27.3544304, -21.2336449, -22.9245283)
#add a broader group variable (e.g. size)
group_of_eq <- c("small", "medium", "medium", "medium", "large")
eq_df <- data.frame(equation_id, slope, intercept, group_of_eq)
#create some test data
group <- c("A", "B", "C", "A")
iso_value_p <- c(14, 12, NA, 13.5)
#add a broader group variable (e.g. size)
group_broad <- c("medium", "medium", "small", "large")
data_df <- data.frame(group, iso_value_p, group_broad)
#group_of_eq and group_broad should have spectra of levels that can be matched together
##[not working] (for question 1):
#Provided that eq_df is present in the environment, we can create a function
data_conversion_with_groups <- function(x, choose_group) {
inds <- eq_df$group_of_eq %in% choose_group
eq_df$slope[inds] * x + eq_df$intercept[inds]
}
data_conversion_with_groups(iso_value_p, "medium")
#[1] 23.32203 -12.16456 NA 22.47458
#it should return only 2 values (the 1st and 2nd row in data_df); and it gives an error-message:
#1: In eq_df$slope[inds] * x :
# longer object length is not a multiple of shorter object length
#2: In eq_df$slope[inds] * x + eq_df$intercept[inds] :
# longer object length is not a multiple of shorter object length
我正在寻找以下内容:
对于1):对于data_conversion_with_groups(iso_value_p, "medium")
,我期望一个长度为3的向量(使用eq_df中的第2-4行)。
理想情况下,应将它们分别编码为列。
对于2):对于data_df的第一行(在group_broad列中包含“中” als值),我希望得到相同的结果。区别在于,该组被自动调用。