I want to write a function that adds a new variable to a data frame. That new variable constist in the concatenation of values corresponding to a set of variables passed in argument (as vector of strings). In base R, I would write something like:
addConcatFields<-function(data,listOfVar)
{
data$uniqueId=data[,listOfVar[1]]
for(elt in listOfVar[2:length(listOfVar)])
{
data$uniqueId=paste(data$uniqueId,data[,elt],sep='_')
}
return(data)
}
addConcatFields(iris,c('Petal.Width','Species'))
# gives:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species uniqueId
1 5.1 3.5 1.4 0.2 setosa 0.2_setosa
2 4.9 3.0 1.4 0.2 setosa 0.2_setosa
...
My initial goal was to make it using dplyr::mutate and despite I read the programming vignette http://127.0.0.1:31671/library/dplyr/doc/programming.html, I did not manage to reach my goal. Because I want to understand the point I missed, I would like to solve the problem using mutate and I would appreciate suggestions.