2012-01-30 65 views
0

我有一個數據集,看起來像:
order year value
1 1990 2
1 1990 1
1 1990 1
2 1990 0
3 1990 4
1 1991 3
2 1991 2
2 1991 0
[R計算行數的組合

我一直在試圖讓在特定年份獨特的訂單數。我試圖table(data$year)這給了我:
1990 1991
5 3

不過,我想獲得:

1990 1991
3 2

回答

4

這將這樣的伎倆。它使用tapply()分別計算year的每個級別的order的唯一值的數量。

df <- read.table(text="order year value 
1 1990 2 
1 1990 1 
1 1990 1 
2 1990 0 
3 1990 4 
1 1991 3 
2 1991 2 
2 1991 0", header=T) 

with(df, tapply(order, year, function(X) length(unique(X)))) 
# 1990 1991 
# 3 2 
2

必要plyr和data.table選項:

dat <- read.table(text = txt, header = TRUE) 

library(plyr) 
ddply(dat, "year", summarize, val = length(unique(order))) 

library(data.table) 
dt <- data.table(dat) 
dt[, length(unique(order)), by = year] 
0

這也可以通過調用unique訂單table來完成,而不是具體的人。

table(unique(df[,c("order","year")])$year)