1

I have the dataframe below:

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

From this dataframe I want to extract the unique values of the Name and then count how many Target each unique Name has in order to create a second dataframe like:

Name NumberofTargets
1   BO               1
2   DF               2
3   FG               1
4   GH               1
firmo23
  • 6,014
  • 1
  • 20
  • 70

1 Answers1

1

We group by 'Name' and get the number of distinct elements (n_distinct) of 'Target'

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
akrun
  • 789,025
  • 32
  • 460
  • 575