I want to create a new column, which contains the totals count of a unique instance of another column.
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
What I want is the following:
# x y z
#
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 2 N 3
# 2 N 3
# 2 Y 3
# 3 Y 3
# 3 Y 3
# 3 Y 3
# 4 Y 2
# 4 Y 2
# 5 Y 1
# 6 N 3
# 6 Y 3
# 6 Y 3
I have done the following script but it is convuluted.
library(plyr)
library(dplyr)
library(purrr)
library(tidyverse)
library(ggtext)
library(stringr)
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
unique_count <- as.data.frame(table(df$x))
colnames(unique_count)[1] <- "x"
colnames(unique_count)[2] <- "z"
df <- purrr::reduce(list(df,unique_count), dplyr::left_join, by = 'x')