提取一列的唯一值,并计算与第一个数据帧相关的同一数据框的第二个列的值

时间:2018-11-30 16:48:27

标签: r

我的数据框如下:

Name<-c("BO","DF","FG","GH","BO","DF")
Target<-c("sd","vc","vc","dd","sd","jk")
NT<-data.frame(Name,Target)

我要从此数据帧中提取Name的唯一值,然后计算每个唯一Target拥有多少Name,以便创建第二个数据帧,例如:

Name NumberofTargets
1   BO               1
2   DF               2
3   FG               1
4   GH               1

1 个答案:

答案 0 :(得分:1)

我们按“名称”分组并获得“目标”的distinct个元素(n_distinct)的数量

library(dplyr)
NT %>%
   group_by(Name) %>%
   summarise(NumberofTargets = n_distinct(Target))
# A tibble: 4 x 2
#  Name  NumberofTargets
#  <fct>           <int>
#1 BO                  1
#2 DF                  2
#3 FG                  1
#4 GH                  1