如何在R中按条件编写具有多个函数和多个变量的for(){}循环? 我有一个看起来像这样的数据集。。。。还有更多的变量。。。

如何在R中按条件编写具有多个函数和多个变量的for(){}循环? 我有一个看起来像这样的数据集。。。。还有更多的变量。。。,r,R,但是我只对使用for(){}命令对其中四个运行一些统计信息感兴趣。。。。。数据集=b1 ELEV SLOPE ASPECT presab 2342.569 0.297 109.502 1 2280.851 0.997 106.433 2 2281.271 0.665 93.872 1 2277.854 2.407 215.193 2 2271.858 1.132 32.050 1 2229.149 0.000

但是我只对使用for(){}命令对其中四个运行一些统计信息感兴趣。。。。。数据集=b1

ELEV   SLOPE    ASPECT     presab
2342.569   0.297   109.502   1 
2280.851   0.997   106.433   2
2281.271   0.665    93.872   1
2277.854   2.407   215.193   2
2271.858   1.132    32.050   1
2229.149   0.000   270.000   1
使用for(){}如何循环多个统计函数(平均值、标准差、长度)到; 多变量(标高、坡度、坡向); 主席团; 并将其导出为工作环境中的三个R对象

这是我所能做到的。。。。。有人能帮忙吗? 首先我试过这个。。。。。这有点奏效

>i=1
>for (i in 1:1) {
    v1=tapply(b1$ASPECT,b1$presab,mean)
    v2=tapply(b1$ELEV,b1$presab,mean)
    v3=tapply(b1$SLOPE,b1$presab,mean)
    v4=cbind(v1,v2,v3)
    print(v4)}

#        v1       v2       v3
#1 137.3997 2400.974 4.075000
#2 131.2396 2400.301 3.306509
我也试过这种格式。。。。
任何面包屑都可以帮助我找到回家的路……一种使用自定义函数和
plyr
包的方法

首先,构建一个函数,用于计算所选的摘要统计信息,并作为命名向量返回:

statistics <- function(x, na.omit=TRUE){
  fun_names <- c("Length", "Mean", "SD")

  if(na.omit)
    x <- x[!is.na(x)]

  n <- length(x)
  m <- mean(x)
  s <- sd(x)

  stats <- c(n,m,s)
  names(stats) <- fun_names
  return(stats)
}
这里有一个小的解释:ddply将把data.frame
b1
presab
值拆分,并将(匿名)函数应用于每个值中。此函数将计算
b1
中存在的所有数值变量的统计信息。
sapply(df,is.numeric)
部分确保仅尝试计算数值变量的摘要

希望有帮助

谢谢大家的发帖! 我找到了一种使用for(){}函数循环的方法来构建一个运行良好的矩阵
>ex17out
statistics <- function(x, na.omit=TRUE){
  fun_names <- c("Length", "Mean", "SD")

  if(na.omit)
    x <- x[!is.na(x)]

  n <- length(x)
  m <- mean(x)
  s <- sd(x)

  stats <- c(n,m,s)
  names(stats) <- fun_names
  return(stats)
}
library(plyr)

summary <- ddply(b1, "presab", function(df) statistics(df[ , sapply(df, is.numeric)]))
>ex17out <- matrix(0,3,6)
for (i in 1:2) {
  temp <- subset(b3,presab==i)
  ex17out[1,i*3-2] <- mean(temp$ASPECT)
  ex17out[1,i*3-1] <- sd(temp$ASPECT)
  ex17out[1,i*3] <- length(temp$ASPECT)
  ex17out[1,i*3-2] <- mean(temp$ASPECT)
  ex17out[1,i*3-1] <- sd(temp$ASPECT)
  ex17out[1,i*3] <- length(temp$ASPECT)
  ex17out[2,i*3-2] <- mean(temp$ELEV)
  ex17out[2,i*3-1] <- sd(temp$ELEV)
  ex17out[2,i*3] <- length(temp$ELEV)
  ex17out[2,i*3-2] <- mean(temp$ELEV)
  ex17out[2,i*3-1] <- sd(temp$ELEV)
  ex17out[2,i*3] <- length(temp$ELEV)
  ex17out[3,i*3-2] <- mean(temp$SLOPE)
  ex17out[3,i*3-1] <- sd(temp$SLOPE)
  ex17out[3,i*3] <- length(temp$SLOPE)
  ex17out[3,i*3-2] <- mean(temp$SLOPE)
  ex17out[3,i*3-1] <- sd(temp$SLOPE)
  ex17out[3,i*3] <- length(temp$SLOPE)
  }
>ex17out
 

           [,1]      [,2] [,3]       [,4]       [,5] [,6]
[1,]  131.599609 86.628193   46  135.00713  75.039541  182
[2,] 2276.916891 44.433890   46 2431.90777 179.167677  182
[3,]    4.066087  4.654311   46    3.59589   4.826945  182