Reputation: 51
I have a numeric vector of 5 radii. I wrote the following function to calculate the area of a circle if one of the arguments in my function = 'AC'. I want to write a loop that using my function to calculate the area of a circle using radii in a numeric vector and print the results. How do I go about solving my problem in R?
Function:
area.volume =function(var1,R) {
if (toupper(var1)=='AC') {
pi*R^2
} else if (toupper(var1)=='CC') {
4/3*pi*R
} else if (toupper(var1)=='VS') {
4*pi*R^2
} else print("your method is not supported")
}
Vector of radii: c(20,10,4,34)
I would like my function to loop through the vector and calculate the are using the line:
if (toupper(var1)=='AC'){ pi*R^2 }
.
Upvotes: 0
Views: 10847
Reputation: 2939
your function already fulfills your spec through vectorization:
area.volume('AC', c(20,10,4,34))
[1] 1256.63706 314.15927 50.26548 3631.68111
Upvotes: 1