I have a dataframe my_df
and I would like to add an additional column, my_new_column
, and populate it with random integer numbers that add up to a given sum.
Here is some reproducible code:
library(dplyr)
library(magrittr)
my_df <- as.data.frame(matrix(nrow = 10, ncol = 2))
colnames(my_df) <- c("Cat", "MarksA")
my_df$Cat <- LETTERS[1:nrow(my_df)]
my_df$MarksA <- sample(1:100, size = nrow(my_df))
In Tidyverse
style, I tried the following:
my_df %<>% mutate(my_new_column=sample(n()))
However, this gives me a column which sums up to an arbitrary number. How can I tweak my code to achieve this task?