0

Hello everyone I am fairly new to r programming and i was wondering if someone could help me out. I was just playing with r and wanted to make a function that returned a vector of the means of each column in a data set that the user would put in as an argument. The problem is I am trying to do it without the mean r the apply functions so I am just manually trying it out and feel I am very close to finishing it. Just wanted to ask if someone could check it to see where I made an error. Here is my code:

findMeans<- function(data)
{
  meanVec <- numeric()
  for(i in 1:6)
  {
    mean=0
    for( j in 1:153)
    {
      value=0
      count=0
      if(is.na(data[j,i])==FALSE)
      {
        value= value + data[i,j]
        count=count+1
      }
      else
      {
        value= value +0
      }
    }
    mean =value/count
    meanVec[i]<-mean


  }
  meanVec



} 

and when I try to list the vector it just gives this

> meanVec
numeric(0)

could anyone possibly shed some light on what I am doing wrong?

yesman89
  • 15
  • 2
  • 5
    `colMeans` is a thing. – alistaire Jun 24 '16 at 17:45
  • yes i know about the colMeans function, i just wanted to do it without any of those kinds of function and practice my for loops and also vector creation – yesman89 Jun 24 '16 at 17:48
  • 1
    if practice is seeked, maybe provide data as sample, ready to be run, or use a public dataset reference? Looping with hardcoded 1:6 and 1:153 suggest to identify the next targets for trying to be more generic, when coding self a solution instead of using a generic ready made contributed function ;-) – Dilettant Jun 24 '16 at 17:51
  • 1
    @Dilettant oh i am sorry i left that information out, in r it shows the dimensions in the environment, but in the future i would make it generics, there are 6 columns and 153 rows in the data set – yesman89 Jun 24 '16 at 18:03
  • Welcome to SO, there are great meta resources here eg. [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Dilettant Jun 24 '16 at 18:07

1 Answers1

0

If you're looking for function writing practice, and are already aware of the colMeans function, there's a couple errors I spotted.

1) I assume that when you're going from 1:6, you're going through each column in your data frame, and 1:153, you're going through each row. If this is accurate, your value=0 and count = 0 statements should be moved a level up, next to mean = 0. Otherwise, you're resetting the value to zero every row you go through, which won't do anything but report the last value it comes across.

2) In the line value= value + data[i,j], you need data[j,i] instead. You reversed the row and column values.

With those two changes, your function seems to work for a data set with 6 columns and 153 rows. For more practice, I'd recommend trying to find a way to generalize the function for any number of columns and rows.

Sam
  • 1,353
  • 18
  • 22