2014-01-21 66 views
3

我有一個名爲長度爲166860的數字區域。它由412個不同的元素組成,大部分長度爲405,部分長度爲809.我有它們的開始和結束ID。在矩陣/數據幀中保存不同長度的向量

我的目標是提取它們,並把它們放在一個矩陣/數據幀有412列

現在,我想這樣的代碼:

m = matrix(NA,ncol=412, nrow=809) 
for (j in 1:412){ 
temp.start = start.ids[j] 
temp.end = end.ids[j] 
m[,j] = area[temp.start:temp.end] 
} 

但我剛剛結束了與此錯誤消息:

「以m錯誤[,J] =面積[temp.start:temp.end]: 數項替換的是不替換長度的倍數」

+0

通常你把它們放入一個列表(這使得它的元素,具有不同的長度),或創建一個id列和值列一個長格式data.frame。我會做後者。 – Roland

回答

3

這裏有一個很簡單的方法:

示例數據:

area <- c(1:4, 1:5, 1:6, 1:3) 
# [1] 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 

start.ids <- which(area == 1) 
# [1] 1 5 10 16 

end.ids <- c(which(area == 1)[-1] - 1, length(area)) 
# [1] 4 9 15 18 

創建一個行矩陣列表:

mats <- mapply(function(x, y) t(area[seq(x, y)]), start.ids, end.ids) 
# [[1]] 
#  [,1] [,2] [,3] [,4] 
# [1,] 1 2 3 4 
# 
# [[2]] 
#  [,1] [,2] [,3] [,4] [,5] 
# [1,] 1 2 3 4 5 
# 
# [[3]] 
#  [,1] [,2] [,3] [,4] [,5] [,6] 
# [1,] 1 2 3 4 5 6 
# 
# [[4]] 
#  [,1] [,2] [,3] 
# [1,] 1 2 3 

使用plyr包中的函數rbind.fill.matrix創建矩陣和轉置它(t):

library(plyr) 
m <- t(rbind.fill.matrix(mats)) 
# [,1] [,2] [,3] [,4] 
# 1 1 1 1 1 
# 2 2 2 2 2 
# 3 3 3 3 3 
# 4 4 4 4 NA 
# 5 NA 5 5 NA 
# 6 NA NA 6 NA 
0

W¯¯帽子約

m[j,] = area[temp.start:temp.end] 

編輯:

a <- area[temp.start:temp.end] 
    m[1:length(a),j] <- a 
+0

返回相同的錯誤消息不幸 「錯誤以m [J,] =面積[temp.start:temp.end]: 數項替換的是不替換長度的倍數」 – user2846211

+0

@ user2846211酵母這是笨。有一個錯誤的想法。那編輯怎麼樣? – lukeA

0

也許別人有更好的答案。在我看來,你有兩個選擇:

  1. 變化M [,J]到M [1:長度(區[temp.start:temp.end]),J],然後你不會得到一個錯誤,但你會留下一些NA。

  2. 使用矩陣列表來代替,因此您會爲每個矩陣獲得不同的維度。

+0

我試過後面的選項,我仍然得到這個錯誤: 「m [length(area [temp.start:temp.end]),j] = area [temp.start:temp.end]中的錯誤: number的項目替換不是替換長度的倍數「 – user2846211

+0

好的,我編輯了我的評論,對不起。其他人建議不要使用矩陣對我來說似乎也更合理。 – Daniel

1

您正在將列長度設置爲412,並且矩陣的長度不能是靈活/可變的。這意味着分配給列的值必須具有412的長度或東西少,可以填補到412的長度從手冊上矩陣:

If there are too few elements in data to fill the matrix, then the elements in data are recycled. If data has length zero, NA of an appropriate type is used for atomic vectors (0 for raw vectors) and NULL for lists.

正如一位網民說,你可能有打算分配給行,在這種情況下,m [j,]是做這件事的方法,但是你必須填寫你指定的值爲NA或允許填充NA,所分配的值總是長度爲809 。

m = matrix(NA,ncol=412, nrow=809) 
for (j in 1:412){ 
    temp.start = start.ids[j] 
    temp.end = end.ids[j] 
    val <- area[temp.start:temp.end] 
    m[j, ] = c(val, rep(NA, 809 - length(val))) 
} 
1

這個怎麼樣?我製造了一些樣本數據:

#here are the random sets of numbers - length either 408 or 809 
nums<-lapply(1:412,function(x)runif(sample(c(408,809),1))) 

#this represents your numeric (one list of all the numbers) 
nums.vec<-unlist(nums) 

#get data about the series (which you have) 
nums.lengths<-sapply(nums,function(x)length(x)) 
nums.starts<-cumsum(c(1,nums.lengths[-1])) 
nums.ends<-nums.starts+nums.lengths-1 


new.vec<-unlist(lapply(1:412,function(x){ 
    v<-nums.vec[nums.starts[x]:nums.ends[x]] 
    c(v,rep(0,(809-length(v)))) 
})) 

matrix(new.vec,ncol=412)