dataframe—按列查找一列中具有相同值的行的不同值计数
对于下面的示例数据帧,我需要找到每个dataframe—按列查找一列中具有相同值的行的不同值计数,r,R,对于下面的示例数据帧,我需要找到每个id——每列的不同值的计数 df <- data.frame(id = c(2,2,3,3,3,1,1,4,4), prop1 = c("A","A","B","B","B","B","B","B","C"), prop2 = c(FALSE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE,FALSE),
id
——每列的不同值的计数
df <- data.frame(id = c(2,2,3,3,3,1,1,4,4),
prop1 = c("A","A","B","B","B","B","B","B","C"),
prop2 = c(FALSE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE,FALSE),
prop3= c(4,4,3,3,4,5,1,5,1))
> df
id prop1 prop2 prop3
1 2 A FALSE 4
2 2 A FALSE 4
3 3 B FALSE 3
4 3 B FALSE 3
5 3 B FALSE 4
6 1 B TRUE 5
7 1 B FALSE 1
8 4 B TRUE 5
9 4 C FALSE 1
您可以在
aggregate
中对不重复的案例进行sum
,这样您就可以根据id
进行分组:
aggregate(. ~ id, df, function(x){ sum(!duplicated(x)) })
## id prop1 prop2 prop3
## 1 1 1 2 2
## 2 2 1 1 1
## 3 3 1 1 2
## 4 4 2 2 2
或者使用length(unique(…)
如果对您更有意义:
aggregate(. ~ id, df, function(x){length(unique(x))}) # returns identical result
如果读者关心,在dplyr中应该是
library(dplyr)
df %>% group_by(id) %>% summarise_all(n_distinct)
或data.table
library(data.table)
setDT(df)[, lapply(.SD, uniqueN), by = id]
您可以在aggregate
中对不重复的案例进行sum
,这样您就可以根据id
进行分组:
aggregate(. ~ id, df, function(x){ sum(!duplicated(x)) })
## id prop1 prop2 prop3
## 1 1 1 2 2
## 2 2 1 1 1
## 3 3 1 1 2
## 4 4 2 2 2
或者使用length(unique(…)
如果对您更有意义:
aggregate(. ~ id, df, function(x){length(unique(x))}) # returns identical result
如果读者关心,在dplyr中应该是
library(dplyr)
df %>% group_by(id) %>% summarise_all(n_distinct)
或data.table
library(data.table)
setDT(df)[, lapply(.SD, uniqueN), by = id]