2017-09-03 88 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