0

Can anyone please suggest how to mutate a new column based on dataset name? Below is my code:

WK20 <- data.frame(cbind(c("A","B","C","D","E"),c("135373","135530","72082","100029","19719"), c("484576.90","476355.44","249807.60","354968.68","67386.69")),stringsAsFactors = F)

WK20 <- WK20 %>%
rename("STORE ID" = X1,
     "TOTAL UNIT" = X2,
     "TOTAL SALES" = X3) %>%
melt(id="STORE ID") %>% 
mutate(WK = names(data.frame()))

The expected output is to have the name of dataset in object of WK. I run the code and get the error "Error: Column WK must be length 10 (the number of rows) or one, not 0".

Expected output is:

enter image description here

JonSirNo
  • 67
  • 5
  • What do you intend to happen with `names(data.frame())`? You're creating an empty data frame – camille Sep 26 '19 at 04:02
  • I edited the question. Thanks for notifying me. – JonSirNo Sep 26 '19 at 04:08
  • I don't have the answer to your question (not sure if its possible), but if the goal is to bind after multiple dataframes and this column is used to remember where each row comes from, this easiest way to do that is to create a list of dataframes and use `bind_rows` function with `.id` argument – fmarm Sep 26 '19 at 04:08
  • Maybe you need this ? https://stackoverflow.com/questions/42560389/get-name-of-dataframe-passed-through-pipe-in-r – Ronak Shah Sep 26 '19 at 04:12
  • Please try `substitute(WK20)` or `quote(WK20)`. It gives a symbol then do `deparse` around to get a string – Clemsang Sep 26 '19 at 06:37

0 Answers0