Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Automate using a function in R

I have a dataset where I need to do the following steps for analysis.

a <- with(iris, sum(Petal.Length[Petal.Width<0.2]))
b <- with(iris, sum(Petal.Length[Petal.Width<0.7]))
cc <- with(iris, sum(Petal.Length[Petal.Width<1]))
d <- with(iris, sum(Petal.Length[Petal.Width<3]))

e<-(b-a)
f<-(cc-b)
g<-(d-cc)

newdata <- data.frame(x=c(1,2,3),y=c(e,f,g))

I now need to calculate the same by replacing Petal.Length to Sepal.Length and so on. Therefore I wrote a function for this but I get the error 'Sepal.Length' not found when using h<- myfun(iris,Sepal.Length). Any help is appreciated.

myfun <- function(mydata,myvar){
  res <- NULL
  a <- with(mydata, sum(myvar[Petal.Width<0.2]))
  b <- with(mydata, sum(myvar[Petal.Width<0.7]))
  cc <- with(mydata, sum(myvar[Petal.Width<1]))
  d <- with(mydata, sum(myvar[Petal.Width<3]))
  
  e<-(b-a)
  f<-(cc-b)
  g<-(d-cc)
  
  res <- c(e,f,g)
  
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a simple fix. Remember to put the return in the function. When you pass input arguments, myvar should be in the form of character

myfun <- function(mydata,myvar){
  a = sum(mydata[mydata[,"Petal.Width"] < 0.2 ,myvar])
  b = sum(mydata[mydata[,"Petal.Width"] < 0.7 ,myvar])
  c = sum(mydata[mydata[,"Petal.Width"] < 1 ,myvar])
  d = sum(mydata[mydata[,"Petal.Width"] < 3 ,myvar])
  
  e<-(b-a)
  f<-(c-b)
  g<-(d-c)
  
  return(c(e,f,g))
  
}

myfun(iris,"Petal.Length")

If you want to write it using the functions already present in R you can use cut which divides a numerical variable into intervals, and then via sapply adds Petal.Length for each interval.

lev = c(0.2,0.7,1,3)
cutPoint = cut(iris$Petal.Width,
               breaks = c(min(iris$Petal.Width),0.2,0.7,1,3),
               labels = lev,
               right = F)
sapply(1:4, function(i) sum(iris$Petal.Length[cutPoint == lev[i]]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading