在循环中填充R中的数据帧 [英] Populating a data frame in R in a loop

查看:147
本文介绍了在循环中填充R中的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从R中的for循环中填充数据帧。列的名称在循环内动态生成,并且一些循环变量的值在填充数据帧时用作值。例如,当前列的名称可以是循环中的一个字符串的变量名,列可以将当前迭代器的值作为数据帧中的值。



我试图在循环之外创建一个空数据框,像这样

  d = data.frame()

但是,我无法做任何事情,当我尝试填充它的时候,我遇到了一个错误

  d [1] = c(1,2)
`(`* tmp *`,1,value = c(1,2)):
替换有2行,数据有0

什么可能是一个很好的方式来实现我想要做的事情。如果我不清楚,请让我知道。

解决方案

你可以这样做:

  iterations = 10 
variables = 2

output< - matrix(ncol = variables,nrow = iterations)

for(i in 1:iterations){
output [i,]< - runif(2)

}

输出

,然后将其转换为 data.frame / p>

 输出<  -  data.frame(输出)
类(输出)

这样做:


  1. 创建一个矩阵根据预期增长的行和列

  2. 将2个随机数插入矩阵

  3. 将其转换为 之后的数据框循环已完成。


I am trying to populate a data frame from within a for loop in R. The names of the columns are generated dynamically within the loop and the value of some of the loop variables is used as the values while populating the data frame. For instance the name of the current column could be some variable name as a string in the loop, and the column can take the value of the current iterator as its value in the data frame.

I tried to create an empty data frame outside the loop, like this

d = data.frame()

But I cant really do anything with it, the moment I try to populate it, I run into an error

 d[1] = c(1,2)
Error in `[<-.data.frame`(`*tmp*`, 1, value = c(1, 2)) : 
  replacement has 2 rows, data has 0

What may be a good way to achieve what I am looking to do. Please let me know if I wasnt clear.

解决方案

You could do it like this:

 iterations = 10
 variables = 2

 output <- matrix(ncol=variables, nrow=iterations)

 for(i in 1:iterations){
  output[i,] <- runif(2)

 }

 output

and then turn it into a data.frame

 output <- data.frame(output)
 class(output)

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.

这篇关于在循环中填充R中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆