简体   繁体   English

将行添加到R中的空数据框中时出错

[英]Error in adding rows to an empty data frame in R

CREATING AN EMPTY DATA FRAME: 创建一个空数据帧:

data <- data.frame(ticks = numeric(0), identity = numeric(0), p_h = numeric(0), p_y = numeric(0), v_x = numeric(0), v_y = numeric(0), size = numeric(0), homo = numeric(0))

ADDING DATA TO DATA FRAME: 将数据添加到数据帧:

while (x < timeStepsToRun)
{
.....
data[i, ] <- c(ag$ticks, ag$who, ag$xcor, ag$ycor, ag$v-x, ag$v-y,"10","1")
i=i+1;
...
}

THOUGH I GET THE FOLLOWING ERROR WHEN ADDING DATA: 我在添加数据时遇到以下错误:

Error in value[[jvseq[[jjj]]]] : subscript out of bounds
In addition: Warning message:
In matrix(value, n, p) : data length exceeds size of matrix

Please suggest a better strategy or help me in correcting the above. 请提出更好的策略或帮助我纠正上述问题。 Thanks in advance! 提前致谢!

If you know how large you need your data.frame to be, prespecify the size, then you won't encounter these kind of errors: 如果您知道data.frame的大小,请预先指定大小,那么您将不会遇到以下类型的错误:

rows <- 1e4 # it's not clear how many you actually need from your example
data <- setNames(as.data.frame(matrix(nrow = rows, ncol = 8))
                 c('ticks', 'identity', 'p_h', 'p_y', 'v_x', 'v_y', 'size', 'homo'))

Then you can fill it in the way that you describe. 然后,您可以按照您描述的方式填写它。 Even creating a dataframe larger than the one you need and cutting it down to size later is more efficient than growing it row by row. 即使创建一个比您需要的数据帧更大的数据帧,然后在以后将其缩减为大小,也比逐行增长它更有效。

If you know the classes of the columns you are going to create it can also be performance-enhancing to prespecify the column classes: 如果您知道要创建的列的类别,则可以提高性能以预先指定列的类别:

rows <- 1e4
data <- data.frame(ticks = integer(rows), 
                   identity = character(rows), 
                   p_h = numeric(rows), 
                   p_y = numeric(rows), 
                   v_x = numeric(rows), 
                   v_y = numeric(rows), 
                   size = numeric(rows), 
                   homo = numeric(rows))

I gotchu: 我得:

data <- data.frame(ticks=NA, identity=NA, p_h=NA, p_y=NA, v_x=NA, v_y=NA, 
                  size=NA, homo=NA)

timeStepstoRun <- 10
x <- #something
i <- 1

while (x < timeStepstoRun) {
  data[i,] <- 1:8
  i <- i + 1
}

Just replace timeStepstoRun , x , and data[x,] <- ... with whatever you actually have. 只需将timeStepstoRunxdata[x,] <- ...替换为您实际拥有的任何东西。 This is never gonna be the good way to do what you're trying to do, but I thought I'd just throw it out. 这永远不是您要尝试做的好方法,但我想我会把它扔掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM