2
m ="jan"  
n = "5e"

r = paste0("jan","5e","_results")


"jan5e_results"

Now I want to use r's value and select a data frame because I have data frame with names like

jan5e_results
feb5e_results
mar5e_results
.
.
.

similarly how do I select column name from those data frames?

e.g.

jan5e_results will have column name jan_var1
feb5e_results will have column name feb_var1
mar5e_results will have column name mar_var1
.
.
.

using variable names how do I select a data frame and column name like

m ="jan"  
n = "5e"
r = paste0("jan","5e","_results")
c = paste0(m,"var1")
r$c

I am asking this because I am trying to make a small utility in shiny which will take input and based on that I need to select specific data frame and specific column. If there is any better way let me know.

Stupid_Intern
  • 3,382
  • 8
  • 37
  • 74

2 Answers2

2

You could also save all dataframes in a list and then select them like this

col= paste0(m,"_var1")
dflist[[r]][col]

#  jan_var1
#1        1
#2        2
#3        3
#4        4
#5        5

The advantage of this approach is that you can create the dataframes dynamically, too. What I mean is: Usually, you need to actually type dataframe names to define them, for example with

jan5e_results <- data.frame(jan_var1 = 1:5, b = 6:10)
# here you can not define jan5e_results without actually writing jan5e_results

But with lists you can simply create dataframes with the names you want to give them inside a list like this

dflist[[r]] <- data.frame(matrix(rnorm(length(somevariable)), ncol= ncol(somedataframe)))

To be able to reproduce it here the whole code including variables from your question

# deciding what elements to choose
r = paste0("jan","5e","_results")
m = "jan" 
col = paste0(m,"_var1")

# vector with dataframe names
dfnames = paste0(c("jan", "feb", "mar"), "5e", "_results")

# creating an empty list
dflist = vector("list", length(dfnames))
# naming the list
names(dflist) = dfnames

# save one of the dataframes to list
dflist[[r]] = data.frame(jan_var1 = 1:5, b = 6:10)
1

We can use get

col= paste0(m,"_var1")
get(r)[col]

#  jan_var1
#1        1
#2        2
#3        3
#4        4
#5        5

get(r) would return the entire dataframe having name as jan5e_results and from that we select col column to subset.

#  jan_var1  b
#1        1  6
#2        2  7
#3        3  8
#4        4  9
#5        5 10

data

jan5e_results <- data.frame(jan_var1 = 1:5, b = 6:10)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • It doesn't works with SpatialPolygonsDataFrame `popup <- paste0("Name: ", shpFile$SUBZONE_N, " ", shpFile_Proj[dfcolName])` >Error in as.character.default() : no method for coercing this S4 class to a vector – Stupid_Intern Apr 07 '19 at 08:12
  • @newguy not sure what might be wrong. Can you add a reproducible example? – Ronak Shah Apr 07 '19 at 08:49