-1

so here is a data frame

a<-data.frame(Brand=c("X","Y","Z","d"),Month=1:4,TRP_A=6:9,TRP_B=7:10,TRP_C=10:7)

In custom function I will need to select one of TRP_A,TRP_B or TRP_C and this will be parameter TRP in function

So let's say I call the function down and as parameter TRP I enter 5 so column TRP_C will be chosen. But it will be named as TRP_C and I need to refer it further e.g. if I want to sum total of the column.

I need to rename TRP_C to general name e.g Target because next time I mights use TPR_B or so... But I don't know how to do it because rename function requires to pass origin name.

    aff<-function(brand,TRP) {

      a<-a%>%select(Brand,Month,TRP)

      total<-a%>%summarise(total=sum(TRP))
      total
    }

aff("X",5)
bullshit
  • 13
  • 1
  • 5
  • The `brand` and `Brand` in your function is different. Are you looking for a function that implements this `a %>% select(Brand, Month, 5) %>% rename(TRP=TRP_C) %>% summarise(total=sum(TRP))` – akrun Jul 25 '15 at 13:03
  • Or do we need to `filter` the 'Brand' rows based on `brand' value and then get the `sum(TRP)` – akrun Jul 25 '15 at 13:09
  • There will be lot of things going on more variable . It's like your first option after selecting columns I want to rename whichever TRP columns is selected to general name which will be reffered to further – bullshit Jul 25 '15 at 13:16
  • May be `aff <- function(brand, TRP1){ a %>% filter(Brand==brand) %>% select(Brand, Month, TRP1) %>% setNames(., c('Brand', 'Month', 'TRP')) %>% summarise(Total=sum(TRP)) }` – akrun Jul 25 '15 at 13:20
  • Thanks Akrun it works ! – bullshit Jul 25 '15 at 13:24

1 Answers1

1

Try

 aff <- function(brand, TRP1){ 
        a %>%
         filter(Brand==brand) %>%
         select(Brand, Month, TRP1) %>% 
         setNames(., c('Brand', 'Month', 'TRP')) %>% 
         summarise(Total=sum(TRP)) }

Or we can change the setNames line to

aff <- function(brand, TRP1){ 
              a %>%
              filter(Brand==brand) %>%
              select(Brand, Month, TRP1) %>% 
              setNames(., sub('\\_.*', '', names(.))) %>%
              summarise(Total = sum(TRP))}
akrun
  • 874,273
  • 37
  • 540
  • 662