问题描述
所以这是一个数据框
a<-data.frame(Brand=c("X","Y","Z","d"),Month=1:4,TRP_A=6:9,TRP_B=7:10,TRP_C=10:7)
在自定义函数中,我需要选择TRP_A,TRP_B或TRP_C之一,这将是函数中的参数TRP
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
因此,假设我调用了该函数,并输入5作为参数TRP,因此将选择列TRP_C。但是它将被命名为TRP_C,我需要进一步引用它,例如如果我想对列的总数求和。
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.
我需要将TRP_C重命名为通用名称,例如Target,因为下次我可能会使用TPR_B左右...但是我不知道该怎么做,因为重命名功能需要传递来源名称。
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)
推荐答案
尝试
aff <- function(brand, TRP1){
a %>%
filter(Brand==brand) %>%
select(Brand, Month, TRP1) %>%
setNames(., c('Brand', 'Month', 'TRP')) %>%
summarise(Total=sum(TRP)) }
或者我们可以更改 setNames
到
aff <- function(brand, TRP1){
a %>%
filter(Brand==brand) %>%
select(Brand, Month, TRP1) %>%
setNames(., sub('\\_.*', '', names(.))) %>%
summarise(Total = sum(TRP))}
这篇关于重命名R中的变量列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!