[英]Error in adding rows to an empty data frame in R
創建一個空數據幀:
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))
將數據添加到數據幀:
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;
...
}
我在添加數據時遇到以下錯誤:
Error in value[[jvseq[[jjj]]]] : subscript out of bounds
In addition: Warning message:
In matrix(value, n, p) : data length exceeds size of matrix
請提出更好的策略或幫助我糾正上述問題。 提前致謝!
如果您知道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'))
然后,您可以按照您描述的方式填寫它。 即使創建一個比您需要的數據幀更大的數據幀,然后在以后將其縮減為大小,也比逐行增長它更有效。
如果您知道要創建的列的類別,則可以提高性能以預先指定列的類別:
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))
我得:
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
}
只需將timeStepstoRun
, x
和data[x,] <- ...
替換為您實際擁有的任何東西。 這永遠不是您要嘗試做的好方法,但我想我會把它扔掉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.