Search code examples
rdataframeshinycbind

new data.frame() from existing using a variable doesn't carry over column name


I want a shiny app to subset my dataframe based on user input. In this case, 'decision' is an input. I use a switch method to get the value of decision. I'm struggling with this because I can't get the colnames() method to work properly on a data frame that is created in a reactive function because the data frame becomes a function and doesn't have columns. As a solution, I'm trying to get the names set before I send it through a reactive function. However, the name of the column when I use a variable to determine which column to pull into my new df does not change, so the following functions are thrown off.

primaryDf <- read.csv('InteractionsFormattedRolling.csv', header = TRUE, sep = ',')
head(primaryDf)

  Month.of.Lifespan Row.Labels Average.of.Event.Value Average.of.Average.Sentiment Average.of.MGT.Fee Sum.of.UniqueID
1                 1         AL                   4.00                         3.00             600.00             311
2                 1         AR                   1.50                         3.00             600.00              83



decision <- "Average.of.Average.Sentiment"
newDf <- data.frame(lifespan = primaryDf$Month.of.Lifespan, label = primaryDf$Row.Labels, decision = primaryDf[decision])
head(newDf)

  lifespan label Average.of.Average.Sentiment
1        1    AL                         3.00
2        1    AR                         3.00
3        1    AZ                         3.00

How can I get the 3rd column of the data.frame to be 'decision'? Am I missing an argument?


Solution

  • You want decision = primaryDf[[decision]].

    Like this, you will only extract the vector of values of the column, not the full column being a list element including the name (data.frames are lists after all).

    Currently decision = is directly being overwritten by the existing name.