gpt4 book ai didi

r - 按组计算基于两列的唯一行数

转载 作者:行者123 更新时间:2023-12-04 12:16:54 25 4
gpt4 key购买 nike

我在r中有一个data.table

    col1 col2 col3   col4
1: 5.1 3.5 1.4 setosa
2: 5.1 3.5 1.4 setosa
3: 4.7 3.2 1.3 setosa
4: 4.6 3.1 1.5 setosa
5: 5.0 3.6 1.4 setosa
6: 5.1 3.5 3.4 eer
7: 5.1 3.5 3.4 eer
8: 5.1 3.2 1.3 eer
9: 5.1 3.5 1.5 eer
10: 5.1 3.5 1.4 eer


DT <- structure(list(col1 = c(5.1, 5.1, 4.7, 4.6, 5, 5.1, 5.1, 5.1,
5.1, 5.1), col2 = c(3.5, 3.5, 3.2, 3.1, 3.6, 3.5, 3.5, 3.2, 3.5,
3.5), col3 = c(1.4, 1.4, 1.3, 1.5, 1.4, 3.4, 3.4, 1.3, 1.5, 1.4
), col4 = structure(c(1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L), .Label = c("setosa",
"versicolor", "virginica", "eer"), class = "factor")), .Names = c("col1",
"col2", "col3", "col4"), row.names = c(NA, -10L), class = c("data.table",
"data.frame"))

我想为 col1的每个值计算 col2col4的唯一(不同)组合。

预期输出为
   col1 col2 col3   col4 count
1: 5.1 3.5 1.4 setosa 4
2: 5.1 3.5 1.4 setosa 4
3: 4.7 3.2 1.3 setosa 4
4: 4.6 3.1 1.5 setosa 4
5: 5.0 3.6 1.4 setosa 4
6: 5.1 3.5 3.4 eer 2
7: 5.1 3.5 3.4 eer 2
8: 5.1 3.2 1.3 eer 2
9: 5.1 3.5 1.5 eer 2
10: 5.1 3.5 1.4 eer 2

如何仅使用1个data.table语法执行此操作?

最佳答案

我必须先进行几次尝试,然后最终完成。有什么好处吗?

DT[, count:=nrow(unique(.SD)), by=col4, .SDcols=c("col1","col2")]
DT
col1 col2 col3 col4 count
1: 5.1 3.5 1.4 setosa 4
2: 5.1 3.5 1.4 setosa 4
3: 4.7 3.2 1.3 setosa 4
4: 4.6 3.1 1.5 setosa 4
5: 5.0 3.6 1.4 setosa 4
6: 5.1 3.5 3.4 eer 2
7: 5.1 3.5 3.4 eer 2
8: 5.1 3.2 1.3 eer 2
9: 5.1 3.5 1.5 eer 2
10: 5.1 3.5 1.4 eer 2
>

和相同但更快的感谢Procrastinatus在下面的评论:
DT[, count:=uniqueN(.SD), by=col4, .SDcols=c("col1","col2")]

关于r - 按组计算基于两列的唯一行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com