【发布时间】:2015-02-23 10:47:01
【问题描述】:
我有两个因子变量 - 在名为“数据”的 data.frame 中 - 看起来像这样:
brand Country
"A" "ITA"
"A" "ITA"
"C" "SPA"
"B" "POR"
"C" "SPA"
"B" "POR"
"A" "ITA"
"D" "ITA"
"E" "SPA"
"D" "ITA"
我想要一个表格,列出country 的唯一brands 的数量。
按照这个例子应该是:
# of unique brands Country
2 "ITA"
2 "SPA"
1 "POR"
首先,我试过了:
data$var <- with(data, ave(brand, Country, FUN = function(x){length(unique(x))}))
但它不适用于因子,所以我转换了我的因子:
data$brand_t<-as.character(data$brand)
data$Country_t<-as.character(data$Country)
然后又一次:
data$var <- with(data, ave(brand_t, Country_t, FUN = function(x){length(unique(x))}))
现在,如果我申请unique(data$var),我会得到"2", "2", "1",这是正确的,但我无法获得我想要的表格。
可能很傻,但我无法解决。
我也想知道是否有更聪明的方法来代替使用因子。
再次感谢。
【问题讨论】: