0
whatpercent <- function(x) {
 i<-1
 for(i in length(x)) {
 if(x[i]<= mean(x)+sd(x)) {
 vec <- c(vec,x[i])
 }
 else{
 next
}
}
percent <- length(vec)/length(x)
percent <- percent * 100
return(percent)
}

Okay I seem to get the same thing when I use

whatpercent(mydata,1) whatpercent(mydata,2) whatpercent(mydata,3) ...

What could be the problem?

Kuantew
  • 134
  • 6
  • 1
    Try `for(i in 1:length(x) ) { .... }`. You do not loop with your code. – Alex Jan 04 '17 at 14:34
  • Yeh ofc! But now this time I get length(vec)>= length(x) – Kuantew Jan 04 '17 at 14:35
  • 3
    You define the function to take one argument, `x`, but you supply it with two arguments when you call it (e.g. `whatpercent(mydata, 1)`). – bouncyball Jan 04 '17 at 14:37
  • As written, the function only checks for values less than or equal to one standard deviation above the mean. Where is the 'k'? – Pierre L Jan 04 '17 at 14:39
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Jan 04 '17 at 14:40

1 Answers1

2

Here is a simple function which should achieve what you want. For tasks like this you should work with vectorized functions in order to avoid loops. It also makes your code much cleaner and easier to read.

whatpercent <- function(x, k) {
    mean(abs(x - mean(x)) <= sd(x) * k)
}

#Example
x <- rnorm(100)
whatpercent(x,2)
[1] 0.95
Frank
  • 66,179
  • 8
  • 96
  • 180
Alex
  • 4,925
  • 2
  • 32
  • 48