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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With