Reputation: 43
How do I return a list from the calculated results? The list must be the same length as the first argument.
circlecalc <- function(var1,R){
if (is.numeric(R) && min(R) >=1){
(toupper(var1)=='AC')
pi*R^2
} else if (toupper(var1)=='CC') {
2*pi*R
} else if (toupper(var1)=='VS') {
4/3*pi*R^3
} else if (toupper(var1)=='AS') {
4*pi*R^2
} else stop ("not valid")
}
Upvotes: 0
Views: 143
Reputation: 522719
The problem with your current approach is that regular if
and else
are not vectorized. You may try using case_when
from the dplyr
package, which is vectorized.
library(dplyr)
circlecalc <- case_when(
is.numeric(R) && min(R) >= 1 && toupper(var1) == 'AC' ~ pi*R^2,
toupper(var1) == 'CC' ~ 2*pi*R,
toupper(var1) == 'VS' ~ 4/3*pi*R^3,
toupper(var1) == 'AS' ~ 4*pi*R^2,
TRUE ~ "not valid"
)
Upvotes: 1