'Mutate several functions pairwise in a generalizable way in R
I have two vectors of names in my database (say one represent a component and second represent values) and I'm trying to develop a function that would create new columns based of the two vectors in a generalizable way I.E. something along the line of :
#vector components and values contain column names from the dataset
creaYK<-function(data,Input="A",Components=c("A", "B", "C"),Values=c("D", "E", "F")){
for(i in 1:length(Values)){
data<-data%>%mutate(new_i = sum(Values[i],Components[i]))
}
}
my problem is that I need my arguments "vec1" and "vec2" to be modifiable in content and length and the calculation to be performed pairwise (each element of vec1 being summed to the corresponding in vec2). I have tried something with across() but it failed.
here is the desired output :
vec1<-c("A","B","C")
vec2<-c("D","E","F")
data<-tibble(A=1,B=2,C=3,D=4,E=5,F=6)
# what I want is a function returning :
# function(data,vec1,vec2)
tibble(A=1,B=2,C=3,D=4,E=5,F=6,ad=5,be=7,cf=9)
But the code above only creates one new column,and my attempts with mutate were also unsuccessful
Moreover, the name of indicators are not structured in the same way as the name of the value used
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
