我有一个数据集,看起来像:
order year value
[R计算行数的组合
1 1990 2
1 1990 1
1 1990 1
2 1990 0
3 1990 4
1 1991 3
2 1991 2
2 1991 0
我一直在试图让在特定年份独特的订单数。我试图table(data$year)
这给了我:
1990 1991
5 3
不过,我想获得:
1990 1991
3 2
我有一个数据集,看起来像:
order year value
[R计算行数的组合
1 1990 2
1 1990 1
1 1990 1
2 1990 0
3 1990 4
1 1991 3
2 1991 2
2 1991 0
我一直在试图让在特定年份独特的订单数。我试图table(data$year)
这给了我:
1990 1991
5 3
不过,我想获得:
1990 1991
3 2
这将这样的伎俩。它使用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
必要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]
这也可以通过调用unique
订单table
来完成,而不是具体的人。
table(unique(df[,c("order","year")])$year)