使用for循环返回变量名称 - R中的变量mean

Ale*_*era 1 database for-loop if-statement r

我正在尝试创建一个for循环,它返回变量名称及其首先提取给定数据库的数字变量.我正在使用mtcars数据库,因此可以使用基本R代码复制:

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
Run Code Online (Sandbox Code Playgroud)

现在,我的想法是循环返回如下所示:

[1] mpg: 20.09062
[1] cyl: 6.1875
[1] disp: 230.7219
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试提取数值变量的名称时,我对所有值都为null:

for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(names(i))
}
}
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
Run Code Online (Sandbox Code Playgroud)

所以,例如:

for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(paste(names(i))," Mean:", mean(i)) 
}
}
Run Code Online (Sandbox Code Playgroud)

显然不起作用.

我知道我可以找到一些更简单的解决方案,但我必须强调,这个问题基本上是为了更深入地讨论循环,所以如果能够使用我公开的代码作为起点给出任何建议,我将不胜感激.

提前致谢.

Ter*_*ror 5

试试这个:

for (i in 1:ncol(mtcars))
{
  if(is.numeric(mtcars[,i]))
  {
    cat(paste(names(mtcars)[i],":",mean(mtcars[,i]),"\n"))
  }
}
Run Code Online (Sandbox Code Playgroud)

你的输出:

mpg : 20.090625 
cyl : 6.1875 
disp : 230.721875 
hp : 146.6875 
drat : 3.5965625 
wt : 3.21725 
qsec : 17.84875 
gear : 3.6875 
carb : 2.8125 
Run Code Online (Sandbox Code Playgroud)