I created a small test dataframe. I want to fill a new column var3 with values. If in the corresponding row var2 = A, the number of A-values from column var2 should be specified. If the corresponding row var2 = B, the number of B values from column var2 is to be specified.
I imagine something like this:
var1 <- c(1,2,3,4,5)
var2 <- c("A","B","B","B","A")
df <- data.frame(var1,var2)
df$var3 <- 0
N_var3 <- df[.N, by = df$var2]
for (i in 1:nrow(df)) {
if (df$var2 == "A") {
df$var3[i] <- N_var3[1]
} else {
df$var3[i] <-N_var3[2]
}
}
the result should be:
df$var3 <- c(2,3,3,3,2)
is there another way without having to use a loop?
Thanks in advance!