How to apply a function to multiple columns and generate a new column as a result?

I have a dataframe with 5 columns. I need to create a 6th column which should be the result of an if-else operation performed on 3 columns from the dataset.

index prediction response lwr upr
23 22.707441 25.0 21.762679 23.65220
86 13.568034 13.0 12.789159 14.34691
96 9.138957 12.0 7.628405 10.64951
111 26.375961 22.0 25.559815 27.19211
121 21.656960 19.0 20.738612 22.57531
140 10.715798 14.0 9.561180 11.87042
153 20.579496 19.0 19.985751 21.17324

I have to create a new column called 'result' to which should be equal to "yes" if the value in 'response' column is higher than the value in 'lwr' column and lesser than the value in 'upr' column for each row.
Else the value should be "no".

library(dplyr)

# Sample data in a copy/paste friendly format, replace this with you own data frame
sample_df <- data.frame(
       index = c(23L, 86L, 96L, 111L, 121L, 140L, 153L),
  prediction = c(22.707441,13.568034,9.138957,26.375961,
                 21.65696,10.715798,20.579496),
    response = c(25, 13, 12, 22, 19, 14, 19),
         lwr = c(21.762679,12.789159,7.628405,25.559815,
                 20.738612,9.56118,19.985751),
         upr = c(23.6522,14.34691,10.64951,27.19211,
                 22.57531,11.87042,21.17324)
)

# Relevant code
sample_df %>% 
    mutate(result = if_else(response > lwr & response < upr, "yes", "no"))
#>   index prediction response       lwr      upr result
#> 1    23  22.707441       25 21.762679 23.65220     no
#> 2    86  13.568034       13 12.789159 14.34691    yes
#> 3    96   9.138957       12  7.628405 10.64951     no
#> 4   111  26.375961       22 25.559815 27.19211     no
#> 5   121  21.656960       19 20.738612 22.57531     no
#> 6   140  10.715798       14  9.561180 11.87042     no
#> 7   153  20.579496       19 19.985751 21.17324     no

Created on 2022-02-16 by the reprex package (v2.0.1)

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Also, if you want to learn more about this, you can read this free online book.

https://r4ds.had.co.nz/

I am getting the following error.
Error in UseMethod("mutate") :
no applicable method for 'mutate' applied to an object of class "c('matrix', 'array', 'double', 'numeric')"

Your data is not in a data frame format, to give you more specific advice please provide a proper reproducible example, as explained on the link I gave you before.

Previous object was in "double" format. Solution works after converting to data frame. Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.