我正在尝试创建一个 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
现在,我的想法是循环返回如下内容:
[1] mpg: 20.09062
[1] cyl: 6.1875
[1] disp: 230.7219
但是,当我尝试提取数字变量的名称时,我得到的所有值都是空值:
for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(names(i))
}
}
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
所以,例如:
for (i in mtcars[,1:length(mtcars)]){
if(is.numeric(i))
{
print(paste(names(i))," Mean:", mean(i))
}
}
显然是行不通的。
我知道我可以找到一些更简单的解决方案,但我必须强调这个问题基本上是为了更深入地了解循环,所以如果可以使用我作为起点公开的代码给出任何建议,我将不胜感激.
提前致谢。
最佳答案
试试这个:
for (i in 1:ncol(mtcars))
{
if(is.numeric(mtcars[,i]))
{
cat(paste(names(mtcars)[i],":",mean(mtcars[,i]),"\n"))
}
}
你的输出:
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
关于r - 使用for循环返回变量名-R中的变量均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901106/