I currently need to create 26 new columns based on 26*2 other columns in my dataframe in R. I don’t think using mutate is an option because the function is a little bit complicated. An example dataframe with fewer columns is
test_dat <- tibble(post1=c(1,3,2),pre1=c(0,3,3),post2=c(3,1,4),pre2=c(3,3,3),post3=c(2,4,1),pre3=c(1,3,2))
I need to generate 3 new columns based on the current columns. Right now, the function I have written to try to accomplish what I need is:
normalized_change <- function(df,post,pre,newcol){
df <- df %>% add_column(newcol = NA)
for(i in 1:nrow(df)){
if(post[i]>pre[i]){
df$newcol[i] <- (post[i]-pre[i])/(4-pre[i])
}
if(post[i]==pre[i]){
df$newcol[i] <- 0
}
if(post[i]<pre[i]){
df$newcol[i] <- (post[i]-pre[i])/pre[i]
}
}
return(df)
}
In order to achieve the desired result, I will have to call the function a total of 3 times, once for each new column I need to generate.
test_dat <- normalized_change(test_dat,test_dat$post1,test_dat$pre1,newcol="norm_change1")
test_dat <- normalized_change(test_dat,test_dat$post2,test_dat$pre2,newcol="norm_change2")
test_dat <- normalized_change(test_dat,test_dat$post3,test_dat$pre3,newcol="norm_change3")
My final test_dat should like like:
tibble(post1=c(1,3,2),
pre1=c(0,3,3),
post2=c(3,1,4),
pre2=c(3,3,3),
post3=c(2,4,1),
pre3=c(1,3,2),
norm_change1=c(0.25,0,-0.33),
norm_change2=c(0,-0.66,1),
norm_change3=c(0.33,1,-0.5)
)
However, the issue is that whenever I run the function normalized_change, the new column is given the name newcol instead of “norm_change1.” In my actual data, I will have to make 26 new columns based on 26*2 current columns. If anyone can give advice on how I can make the function actually generate a column with my preferred name, that would be great. However, if anyone has a more efficient way of doing this that wouldn’t require me calling my function 26 times, that would be even better!
I have tried a number of different things. Mutate functions don’t work because I don’t think they can accept such a complicated function. In order to make my current function work, I have tried things like forcing newcol to be a character which didn’t work.