2017-01-05 37 views
1

如果之前已詢問過此問題,但我已經搜索了一段時間並找不到任何答案來回答我的問題。我對使用R感到有些舒服,但從未真正學過基礎知識。這是我想要做的。R:將矢量中的值與數據框中的列進行比較

我有一個向量(稱之爲「responseTimes」),看起來是這樣的:(它實際上是更長的時間,但我在這裏截斷它)

150 50 250 200 100 150 250 

我還有一個數據框,其中一列timeBin基本上從0開始增加50(因此0 50 100 150 200 250等)。

我想要做的是計算responseTimes中有多少個值小於或等於數據框中的每一行。我想將這些計數存儲在我的數據框的新列中。我的輸出應該是這個樣子:

timeBin counts 
0   0 
50   1 
100  2 
150  4 
200  5 
250  7 

我知道我可以使用SUM函數矢量元素將某個常數(如SUM(responseTimes> 100)會給我5我已經展示了數據這裏),但我不知道如何做到這一點,以比較變化的值(即,比較timeBin列中的每一行)。

我不想使用循環,因爲我被告知這些循環可能特別慢,而且我正在處理一個相當大的數據集。我們歡迎所有的建議!提前致謝。

+0

Perhaphs你需要'table'或'cut',不是很清楚 – akrun

回答

2

您可以使用sapply這樣:

> timeBin <- seq(0, 250, by=50) 
> responseTimes <- c(150, 50, 250, 200, 100, 150, 250) 
> 
> # using sapply (after all `sapply` is a loop) 
> ans <- sapply(timeBin, function(x) sum(responseTimes<=x)) 
> data.frame(timeBin, counts=ans) # your desired output. 
    timeBin counts 
1  0  0 
2  50  1 
3  100  2 
4  150  4 
5  200  5 
6  250  7 
+1

謝謝!這工作完美。感謝幫助。 – sahil

1

這可能會幫助:

responseTimes <- c(150, 50, 250, 200, 100, 150, 250) 
bins1 <- seq(0, 250, by = 50) 


sahil1 <- function(input = responseTimes, binsx = bins1) { 
    tablem <- table(cut(input, binsx)) # count of input across bins 
    tablem <- cumsum(tablem) # cumulative sums 
    return(as.data.frame(tablem)) # table to data frame 
} 
+0

非常有用的非循環解決方案。謝謝! – sahil

+0

不客氣。您可以將行名更改爲箱 –

相關問題