循环以动态填充数据框R

编程入门 行业动态 更新时间:2024-10-23 22:32:41
本文介绍了循环以动态填充数据框R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在运行一个for循环来动态填充数据帧(我知道婴儿密封会死在某个地方,因为我正在使用for循环)

I am running a for loop to fill dynamically a dataframe (I know a baby seal dies somewhere because I am using a for loop)

我有类似这样的内容请注意(5是返回标量的函数的占位符):

I have something like this in mind (the 5 is a placeholder for a function that returns a scalar):

results<-data.frame(matrix(NA, nrow = length(seq(1:10)), ncol = length(seq(1:10)))) rows<-data.frame(matrix(NA, nrow = 1, ncol = 1)) for (j in seq(1:10)){ rows<-data.frame() for (i in seq(1:10)){ rows<-cbind(rows,5) } results<-cbind(results,rows) }

我在上述方法中收到以下错误消息。

I get the following error message with my approach above.

Error in match.names(clabs, names(xi)) : names do not match previous names

有没有更简单的方法?

Is there an easier way?

推荐答案

使用for循环动态地填充对象很好-导致问题的原因是当您动态地使用for循环 build 一个对象(例如,使用 cbind 和 rbind 行)。

Dynamically filling an object using a for loop is fine - what causes problems is when you dynamically build an object using a for loop (e.g. using cbind and rbind rows).

动态构建对象时,R必须在每个循环中为该对象请求新的内存,因为它的大小不断增加。随着对象的变大,这会导致for循环的每次迭代速度变慢。

When you build something dynamically, R has to go and request new memory for the object in each loop, because it keeps increasing in size. This causes a for loop to slow down with every iteration as the object gets bigger.

事先创建对象时(例如 data.frame 具有正确的行数和列数),然后按索引填充,for循环就不会出现此问题。

When you create the object beforehand (e.g. a data.frame with the right number of rows and columns), and fill it in by index, the for loop doesn't have this problem.

一个最后要记住的是,对于 data.frames (和 matrix ),每一列都作为向量存储在内存–因此通常一次将它们填充到一列中会更有效。

One final thing to keep in mind is that for data.frames (and matrices) each column is stored as a vector in memory – so its usually more efficient to fill these in one column at a time.

请牢记所有这些,我们可以如下修改您的代码:

With all that in mind we can revise your code as follows:

results <- data.frame(matrix(NA, nrow = length(seq(1:10)), ncol = length(seq(1:10)))) for (rowIdx in 1:nrow(results)) { for (colIdx in 1:ncol(results)) { results[rowIdx, colIdx] <- 5 # or whatever value you want here } }

更多推荐

循环以动态填充数据框R

本文发布于:2023-08-05 21:23:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!