1

I am trying to make a function that does a simple calculation, however, I want to apply it across several columns, and each column has a different constant in the equation.

enter image description here

This is the formula I want to make into a function.

Example

df<- iris[1:10,2:4]

y_true<- c(3, 1, 0.4)  # each number(constant) corresponds to each column in df 
y_true_sepal_width<- 3 # (1 corresponds to petal.length, 0.4 to petal.width)
R<- 10  # Number of samples
y_estimated<- mean(df$Sepal.Width)


(((sqrt((y_estimated-y_true_sepal_width)^2/R))*100)) #This is (I believe) how to find the value for one column manually 

I want to do this formula, but basically taking the mean of each column and substituting out each y_true as it moves across the data frame. I figured this would be done by putting the true constants into a vector, but haven't had any luck in incorporating it into the function.

hugh_man
  • 399
  • 1
  • 6

1 Answers1

1

Given that you have a df and y_true, you can create an estimate function as follows:

estimate = function(df, y_true) {
        
        R = nrow(df)
        
        y_estimated = apply(df, 2, mean)
        
        ((sqrt( (y_estimated - y_true)^2 / R)) / y_true) * 100
}

and then, you can use it with your data as follows:

df = iris[1:10,2:4]
y_true = c(3, 1, 0.4)

estimate(df = df, y_true = y_true)

which outputs:

Sepal.Width Petal.Length  Petal.Width 
    3.267687    14.230249    14.230249
bird
  • 2,938
  • 1
  • 6
  • 27
  • Sorry what does the 2 in "apply(df, 2, mean)" do? I figured it would just be apply( df, mean), but that throws errors – hugh_man Feb 24 '22 at 14:16
  • 1
    @hugh_man 2 means "apply the `mean` function column-wise" – bird Feb 24 '22 at 14:17
  • Running into one more issue: if we change df to df = iris[1:10,2:5] so it includes Species, how can i take the colMeans by species? I've tried swapping out apply for colMeans, and doing df %>% group_by(species) %>% lapply(df, 2, mean) but neither seems to work. Any ideas? – hugh_man Feb 24 '22 at 14:46
  • 1
    @hugh_man I would create a new post and ask the question there, as it seems like it does not fully match with the original question here. :) – bird Feb 24 '22 at 17:17