문제

I am very new to R and have just started writing smalls functions. here I have written a function that takes data frame as its argument and returns the mean of each column

Code :

n = c(12,13,14,16,16)
m = c(11,2,23,45,67)
a = c(34,343,5,2,1)
b = c(88,33,2,1,44)

db = data.frame (n,m,a,b )

db
   n  m   a  b
1 12 11  34 88
2 13  2 343 33
3 14 23   5  2
4 16 45   2  1
5 16 67   1 44

mean.dataframe = function (df)
{
    for (i in 1:ncol(df))
    {
        j[i]= mean(df[[i]])
    }

    print (j)
}


avgcol = mean.dataframe(db)

Error in j[i] = mean(df[[i]]) : object 'j' not found

I dont understand the error. When I run this in Rstudio it gives this error. However, in R it does not.

도움이 되었습니까?

해결책

This code doesn't work, independently of RStudio. When you type j[i] then R considers the i-th element of j, but j is not defined. Define it before:

mean.dataframe = function (df)
{
    j = rep(NA,ncol(df))
    for (i in 1:ncol(df))
    {
        j[i]= mean(df[[i]])
    }

    print (j)
}

다른 팁

Why don't you just use colMeans?

colMeans (x)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top