2017-09-03 91 views
0

我想用向量:總結在不同長度的原始的矢量結果 - 透視表 - [R

time.int<-c(1,2,3,4,5) #vector to be use as a "guide" 

和數據庫:

time<-c(1,1,1,1,5,5,5) 
value<-c("s","s","s","t","d","d","d") 
dat1<- as.data.frame(cbind(time,value)) 

創建以下載體,然後我可以將第一個向量「time.int」添加到第二個數據庫中。

freq<-c(4,0,0,0,3) #wished result 

該載體是屬於每個時間間隔中的事件的總和,有四個1「時間」,所以第一值獲得一個四等。

可能我想概括一下,這樣我就可以決定間隔,例如,在一個新的向量中總結「times」中的事件每3個time.int數。

編輯泛化

time.int<-c(1,2,3,4,5,6) 
time<-c(1,1,1,2,5,5,5,6) 
value<-c("s","s","s","t", "t","d","d","d") 
dat1<- data.frame(time,value) 

比方說,我希望它每2秒(每2 time.int)

freq<-c(4,0,4) #wished result 

或每3

freq<-c(4,4) #wished result 

我知道如何在Excel中做一個數據透視表。

對不起,如果重複我無法找到一個適合的問題在這個網站上,我甚至不知道如何問這個和從哪裏開始。

回答

4

以下將產生矢量freq

freq <- sapply(time.int, function(x) sum(x == time)) 
freq 
[1] 4 0 0 0 3 

順便說一句,不要使用構造as.data.frame(cbind(.))。而不是

dat1 <- data.frame(time,value)) 

使用爲了概括上述任意長度的time.int段代碼,相信下面的函數將做到這一點。請注意,由於您已更改數據,因此n == 1的輸出與上述內容不同。

fun <- function(x, y, n){ 
    inx <- lapply(seq_len(length(x) %/% n), function(m) seq_len(n) + n*(m - 1)) 
    sapply(inx, function(i) sum(y %in% x[i])) 
} 

freq1 <- fun(time.int, time, 1) 
freq1 
[1] 3 1 0 0 3 1 

freq2 <- fun(time.int, time, 2) 
freq2 
[1] 4 0 4 

freq3 <- fun(time.int, time, 3) 
freq3 
[1] 4 4 
+0

太棒了!如果我想概括一下?爲了能夠在新的向量中說明「times」中的事件,每個3個time.int而不是1個1? –

+0

@havefun也許你可以用嵌套'sapply'來完成,但是你需要編輯你的問題並說出預期的輸出結果。 –

+0

我現在編輯了我的問題,理想情況下我想在開始時選擇一個參數並使用它來分隔向量。 –

1

我們可以使用table函數計算的事件數和使用merge創建一個數據幀總結信息。 event_dat是最終輸出。

# Create example data 
time.int <- c(1,2,3,4,5) 
time <- c(1,1,1,1,5,5,5) 

# Count the event using table and convert to a data frame 
event <- as.data.frame(table(time)) 

# Convert the time.int to a data frame 
time_dat <- data.frame(time = time.int) 

# Merge the data 
event_dat <- merge(time_dat, event, by = "time", all = TRUE) 

# Replace NA with 0 
event_dat[is.na(event_dat)] <- 0 

# See the result 
event_dat 
    time Freq 
1 1 4 
2 2 0 
3 3 0 
4 4 0 
5 5 3