I'm trying to create a for loop which returns both the variable name and its mean first extracting numeric variables of a given database. I'm using the mtcars database so this can be replicated with base R code:
data(mtcars)
# Force 2 variables to factors (if code works fine, output will have 9 rows)
mtcars$vs <- as.factor(mtcars$vs)
mtcars$am <- as.factor(mtcars$am)
# The loop
for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(mean(i))
}
}
#Result (9 rows as expected)
[1] 20.09062
[1] 6.1875
[1] 230.7219
[1] 146.6875
[1] 3.596563
[1] 3.21725
[1] 17.84875
[1] 3.6875
[1] 2.8125
Now, my idea is that the loop returns something like this:
[1] mpg: 20.09062
[1] cyl: 6.1875
[1] disp: 230.7219
But, when I try to extract the names of numeric variables I got null for all values:
for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(names(i))
}
}
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
So, for example:
for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(paste(names(i))," Mean:", mean(i))
}
}
obviously doesn't work.
I'm aware that I can find some easier solutions, but I must emphasize that this question is basically for going more in depth with loops, so I will appreciate if any advice could be given using the code I exposed as starting point.
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire