3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
這是因?yàn)槟鷩L試訪問數(shù)組之外的數(shù)組。
我將向您展示如何調(diào)試此類錯(cuò)誤。
我設(shè)置 options(error=recover)
我跑reach_full_in <- reachability(krack_full, 'in') 我得到:
reach_full_in <- reachability(krack_full, 'in')
Error in reach_mat[i, alter] = 1 : subscript out of bounds
Enter a frame number, or 0 to exit
1: reachability(krack_full, "in")
輸入1,我得到
Called from: top level
我鍵入ls()以查看當(dāng)前的變量
1] "*tmp*" "alter" "g"
"i" "j" "m"
"reach_mat" "this_node_reach"
現(xiàn)在,我將看到變量的尺寸:
Browse[1]> i
[1] 1
Browse[1]> j
[1] 21
Browse[1]> alter
[1] 22
Browse[1]> dim(reach_mat)
[1] 21 21
您會(huì)看到alter已超出范圍。22> 21。在行中:
reach_mat[i, alter] = 1
為避免此類錯(cuò)誤,我個(gè)人這樣做:
嘗試使用applyxx功能。他們比for
我使用seq_along而不是1:n(1:0]
如果可以避免mat[i,j]索引訪問,請(qǐng)嘗試考慮矢量化解決方案。
編輯矢量化解決方案
例如,在這里我看到您沒有使用set.vertex.attribute向量化的事實(shí)。
您可以替換:
# Set vertex attributes
for (i in V(krack_full)) {
for (j in names(attributes)) {
krack_full <- set.vertex.attribute(krack_full, j, index=i, attributes[i+1,j])
}
}
這樣:
## set.vertex.attribute is vectorized!
## no need to loop over vertex!
for (attr in names(attributes))
krack_full <<- set.vertex.attribute(krack_full,
attr, value = attributes[,attr])

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果這對(duì)任何人有幫助,我在將purr :: map()與我編寫的函數(shù)結(jié)合使用時(shí)會(huì)遇到以下問題:
find_nearby_shops <- function(base_account) {
states_table %>%
filter(state == base_account$state) %>%
left_join(target_locations, by = c('border_states' = 'state')) %>%
mutate(x_latitude = base_account$latitude,
x_longitude = base_account$longitude) %>%
mutate(dist_miles = geosphere::distHaversine(p1 = cbind(longitude, latitude),
p2 = cbind(x_longitude, x_latitude))/1609.344)
}
nearby_shop_numbers <- base_locations %>%
split(f = base_locations$id) %>%
purrr::map_df(find_nearby_shops)
有時(shí)我會(huì)在樣本中得到這個(gè)錯(cuò)誤,但是大多數(shù)時(shí)候我不會(huì)。問題的根源是base_locations表(PR)中的某些狀態(tài)不存在于states_table中,因此本質(zhì)上我已經(jīng)過濾掉了所有內(nèi)容,并將一個(gè)空表傳遞給mutate。 這個(gè)故事的寓意是,您可能遇到數(shù)據(jù)問題,而沒有(僅僅是)代碼問題(因此您可能需要清理數(shù)據(jù))。

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
我有時(shí)會(huì)遇到相同的問題。我只能回答你的第二個(gè)要點(diǎn),因?yàn)槲也幌衿渌Z言那樣熟練地使用R。我發(fā)現(xiàn)標(biāo)準(zhǔn)for循環(huán)有一些意外的結(jié)果。說x = 0
for (i in 1:x) {
print(i)
}
輸出是
[1] 1
[1] 0
以python為例
for i in range(x):
print i
什么也沒做。沒有進(jìn)入循環(huán)。
我希望如果x = 0在R中不輸入該循環(huán)。但是,1:0是數(shù)字的有效范圍。除了有一個(gè)if包裝for循環(huán)的語句外,我還沒有找到一個(gè)好的解決方法
- 3 回答
- 0 關(guān)注
- 2335 瀏覽
添加回答
舉報(bào)