我试图从R中的for循环中填充数据帧.列的名称是在循环内动态生成的,并且一些循环变量的值在填充数据框时用作值.例如,当前列的名称可以是某个变量名称作为循环中的字符串,并且该列可以将当前迭代器的值作为其在数据框中的值.
我尝试在循环外创建一个空数据框,就像这样
d = data.frame()
Run Code Online (Sandbox Code Playgroud)
但是我无法对它做任何事情,当我试图填充它时,我遇到了一个错误
d[1] = c(1,2)
Error in `[<-.data.frame`(`*tmp*`, 1, value = c(1, 2)) :
replacement has 2 rows, data has 0
Run Code Online (Sandbox Code Playgroud)
什么是实现我想做的好方法.如果我不清楚,请告诉我.
Rol*_*and 39
通常最好避免循环并使用矢量化函数.如果不可能,有两种方法:
data.frame.建议不要这样做,因为索引很慢data.frames.data.frame后续数据结构.A list在这里非常有用.举例说明一般方法:
mylist <- list() #create an empty list
for (i in 1:5) {
vec <- numeric(5) #preallocate a numeric vector
for (j in 1:5) { #fill the vector
vec[j] <- i^j
}
mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix
Run Code Online (Sandbox Code Playgroud)
在这个例子中没有必要使用a list,你可以预先分配a matrix.但是,如果您不知道循环需要多少次迭代,则应使用a list.
最后,这是示例循环的矢量化替代方案:
outer(1:5,1:5,function(i,j) i^j)
Run Code Online (Sandbox Code Playgroud)
如您所见,它更简单,也更有效.
Seb*_*Seb 34
你可以这样做:
iterations = 10
variables = 2
output <- matrix(ncol=variables, nrow=iterations)
for(i in 1:iterations){
output[i,] <- runif(2)
}
output
Run Code Online (Sandbox Code Playgroud)
然后把它变成一个 data.frame
output <- data.frame(output)
class(output)
Run Code Online (Sandbox Code Playgroud)
这是做什么的:
这也可以。
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
Run Code Online (Sandbox Code Playgroud)
输出将如下所示
df #enter
x y z #col names
1 2 3
Run Code Online (Sandbox Code Playgroud)