Renaming variable column in R

2019-09-21 22:32发布

问题:

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)

回答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))}


标签: r dplyr