原始my.data
:
my.data <- data.frame(
ID = c(1,1,2,2,2),
Value = c(3,4,2.1,3.4,5)
)
ID Value
1 3
1 4
2 2.1
2 3.4
2 5
数据由aggregate
合并,如下所示
consol <- aggregate(Value ~ID, my.data, paste)
consol
看起来像这样:
ID Value
1 c("3", "4")
2 c("2.1", "3.4", "5")
如何计算value
中consol
的元素数量?即使consol[1,2]
显示"3" "4"
,length(consol[1,2])
也会显示1
的值。实际上,Value
列中的所有单元格的长度均为1
。我希望consol[1,2]
的长度为2,consol[2,2]
的长度为3。
答案 0 :(得分:1)
lapply(consol$Value, function(x) length(x))
答案 1 :(得分:0)
元素聚合到列表中。该字段中只有一个列表,但该列表包含多个元素。因此,要获得列表中的元素数量,您需要像这样打开它:
length(consol[1,2][[1]])
另见:
class(consol[1,2])
> [1] "list"
class(consol[1,2][[1]])
> [1] "character"