如何从R输出中创建数据框

3

我正在尝试从多个操作的输出中创建数据集。但我不知道如何自动化这个过程。复制函数很好用,但是需要执行多个操作来获得单个新数据点,例如调整后的R平方和F统计量。

R 代码:

#make dataframe with random data
A<-as.integer(round(runif(20, min=1, max=10)))
dim(A) <- c(10,2)
A<-as.data.frame(A)
#extract F-statistic
summary(lm(formula=V1~V2,data=A))$fstatistic[1]
#extract adjusted R squared
summary(lm(formula=V1~V2,data=A))$adj.r.squared
#repeat 100 times and make a dataframe of the unique extracted output, e.g. 2 columns 100 rows
??????????????

你已经接近成功了... replicate 函数可以很好地工作。只需将两个摘要输出用 c() 包装起来即可。replicate(100, { 我想做的事情; c(summary(lm(formula=V1~V2,data=A))$fstatistic[1], summary(lm(formula=V1~V2,data=A))$adj.r.squared)}) - jbaums
3个回答

1
应用线性模型于5个数据框中... 使用replicate,可以这样做。
> replicate(5, {
      A <- data.frame(rnorm(5), rexp(5))
      m <- lm(formula = A[,1] ~ A[,2], data = A)
      c(f = summary(m)$fstatistic[1], adjR = summary(m)$adj.r.squared)
  })
##               [,1]      [,2]       [,3]      [,4]        [,5]
## f.value  0.4337426 1.3524681 1.17570087 3.8537837  0.04583862
## adjR    -0.1649097 0.0809812 0.04207698 0.4163808 -0.31326721

你可以用 t() 包裹这个操作,得到长格式的矩阵。

你也可以使用广受欢迎的 do.call(rbind, lapply(...)) 方法。

> do.call(rbind, lapply(seq(5), function(x){
      A <- data.frame(rnorm(5), rexp(5))
      m <- lm(formula = A[,1] ~ A[,2], data = A)
      c(f = summary(m)$fstatistic[1], adjR = summary(m)$adj.r.squared)
  }))
##          f.value        adjR
## [1,]   1.9820243  0.19711351
## [2,]  21.6698543  0.83785879
## [3,]   4.4484639  0.46297652
## [4,]   0.9084373 -0.02342693
## [5,]   0.0388510 -0.31628698

你也可以使用sapply函数。

> sapply(seq(5), function(x){
      A <- data.frame(rnorm(5), rexp(5))
      m <- lm(formula = A[,1] ~ A[,2], data = A)
      c(f = summary(m)$fstatistic[1], adjR = summary(m)$adj.r.squared)
  })
##                    [,1]       [,2]          [,3]       [,4]        [,5]
## f.value      0.07245221  0.2076504  0.0003488657 58.5524139  0.92170453
## adjR        -0.30189169 -0.2470187 -0.3331783000  0.9350147 -0.01996465

记住,这些都返回一个“矩阵”(matrix),因此如果您想要一个“数据框”(data.frame)结果,则可能需要使用as.data.frame包装器。

0

只需要用一个 for 循环将它包装起来。

df <- as.data.frame(matrix(0, 100, 2))

for (i in 1:100){
 A<-as.integer(round(runif(20, min=1, max=10)))
 dim(A) <- c(10,2)
 A<-as.data.frame(A)
 #extract F-statistic
 df[i, 1] <- summary(lm(formula=V1~V2,data=A))$fstatistic[1]
 #extract adjusted R squared
 df[i, 2] <- summary(lm(formula=V1~V2,data=A))$adj.r.squared
}

维奥拉。


0

replicate函数将正常工作。首先,编写一个函数来执行您的模拟的一次迭代。

one.sim <- function() {
    A <- matrix(as.integer(runif(20, min=1, max=10)), nrow=10)
    A <- as.data.frame(A)
    m1.summary <- summary(lm(V1 ~ V2, data=A))
    return(c(fstatistic=unname(m1.summary$fstatistic[1]), 
             adj.r.squared=m1.summary$adj.r.squared))
}

然后在replicate中使用这个函数:

results <- t(replicate(100, one.sim()))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接