问题
This question derives from the question and answer given here: How to build a custom function that uses externally defined values with a string condition in R
The remark concerning the combination of 2 equations as an argument makes me curious and brings up 2 following questions:
1) How can I use multiple equations based on another string-value (a grouping variable) which I will add to the eq_df? (expected result: a numeric vector of differing length for each cell in data_df$iso_value_p)
2) If I store this grouping variable into the data_df as well, how is it possible to call for an equation (or several) which is/are matching this grouping variable in eq_df? The code is the following one:
#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
I'm looking for the following:
For 1): For data_conversion_with_groups(iso_value_p, "medium")
I would expect a vector with the length 3 (using 2nd-4th row in the eq_df).
Ideally they should each be coded into columns afterwards.
For 2): In case of the 1st row of data_df (that contains "medium" als value in the group_broad column) I would expect the same result. The difference ist that here, that the group is called taken automatically.
来源:https://stackoverflow.com/questions/55498710/building-a-function-that-dynamically-uses-externally-defined-values-with-a-strin