dmel2017
dmel2017

Reputation: 13

Use variable instead of data table column name reference in sum

I have a table (Table1) with over 200 columns and thousands of rows with numeric data, most of which are months, and the column names are of the format 'Jan 2018', 'Feb 2018' etc.

report[1,2] <- sum(Table1$`Mar 2018`[which(Table1$`Product`=="Apples")])

Instead of using 'Mar 2018', I would like to replace that somehow with a variable name (let's call it searchMonth).

Is this possible?

Upvotes: 1

Views: 511

Answers (1)

akrun
akrun

Reputation: 887391

We can use the [[ to do this

searchMonth <- "Mar 2018"
sum(Table1[[searchMonth]][Table1$Product=="Apples"])

Backquotes or quotes are only needed when there are spaces or special characters in the column names. Otherwise, it can be simply extracted without quoting

Upvotes: 3

Related Questions