I have a set of column names which are as follows
"fb_metrics.3.name"
"fb_metrics.3.period"
"fb_metrics.3.values.0.value.share"
"fb_metrics.3.values.0.value.like"
"fb_metrics.3.values.0.value.comment"
"fb_metrics.3.title"
"fb_metrics.3.description"
There is only one unique value each for the name and period. For example
> df[,"fb_metrics.3.name"]
[1] post_storytellers_by_action_type
Levels: post_storytellers_by_action_type
> df[, "fb_metrics.3.period"]
[1] lifetime
Levels: lifetime
I want to rename column 3,4,5 like this
[1] "post_storytellers_by_action_type.lifetime.share"
[2] "post_storytellers_by_action_type.lifetime.like"
[3] "post_storytellers_by_action_type.lifetime.comment"
I have managed the replacement bit like this
i=3
new_column_name <- paste(as.character(df[1,paste("fb_metrics.",
i,".name", sep = "")]),as.character(df[1,paste("fb_metrics.",
i,".period", sep = "")]), sep = "." )
sub(pattern = ".*value",replacement = new_column_name,x = colnames(df[,
grep(paste("fb_metrics.",i,".values.*",sep = ""), column_names)]))
And I have extracted the columns to be replaced like this
column_names <- colnames(df)
list_of_columns <- colnames(df[,grep("fb_metrics.3.values.*", column_names)])
My question is how should I rename the extracted columns with the column names I just created? Also, is there an easier way to do it?
EDIT:
Ok I renamed it like this
library(data.table)
setnames(df, old = list_of_columns, new = sub(pattern = ".*value",replacement = new_column_name,x = colnames(df[,grep(paste("fb_metrics.",i,".values.*",sep = ""), column_names)])))
But is there a simpler way to do the whole process?