'Issues turning a piece of code into a function

I'm trying to turn a bit of code into a function that can be applied to multiple data sets, but am having some issues.

Code

library(FSA)
library(dplyr)

blg.eqn <- wsVal("Bluegill", units="metric")
lmb.eqn <- wsVal("Largemouth Bass", units="metric")

## filter out individuals below the minimum size
test <- df_new  %>%
  subset(species == "BLG" & length_mm >= blg.eqn$min.TL |
           species == "LMB" & length_mm >= lmb.eqn$min.TL) 

test$W_s <- ifelse(test$species == "BLG",
                   10^(blg.eqn$int + blg.eqn$slope*log10(test$length_mm)), 
                   ifelse(test$species == "LMB", 
                          10^(lmb.eqn$int + lmb.eqn$slope*log10(test$length_mm)), 
                          NA))

## use W_s to calculate relative weight 
test$relative_weight <- (test$wt_g/test$W_s)*100

I want to turn this bit of code into a function so I can put a dataframe of the same format into it and it will just add the relative weight column to it for each observation. I've tried a few variations of the following which doesn't work.

test <- df  %>%
  subset(species == "BLG" & length_mm >= blg.eqn$min.TL |
           species == "LMB" & length_mm >= lmb.eqn$min.TL) 

relative_weight_function <- function(df) {
  df$W_s <- ifelse(df$species == "BLG", 
                   10^(blg.eqn$int + blg.eqn$slope*log10(df$length_mm)), 
                   ifelse(df$species == "LMB", 
                          10^(lmb.eqn$int + lmb.eqn$slope*log10(df$length_mm)),
                          NA))
  df$wr <- (df$wt_g/df$W_s)*100 
}


new <- relative_weight_function(test) %>% rbind()

On this version of code I got it to a point where it returns the correct values, however it drops all other information and put the values into their own column labeled "V1, V2, V3....."

Any help or insight on where I'm going wrong with this would be greatly appreciated.

data

df_new <- structure(list(waterbody = c("Homer", "Homer", "Homer", "Homer", 
"Homer", "Homer", "Homer", "Homer", "Homer", "Homer", "Homer", 
"Homer", "Homer", "Homer", "Homer", "Homer", "Homer", "Homer", 
"Homer", "Homer"), species = c("LMB", "LMB", "GZS", "BLG", "LMB", 
"GZS", "BLG", "BLG", "BLG", "GZS", "BLG", "BLG", "LMB", "GZS", 
"LMB", "LMB", "GZS", "GOS", "LMB", "LMB"), length_mm = c(430, 
430, NA, 165, 345, NA, 128, 117, 93, NA, 135, 161, 402, NA, 347, 
450, NA, NA, 477, 255), wt_g = c(1270, 1325, NA, 108, 545, NA, 
40, 28, 15, NA, 42, 81, 865, NA, 525, 1310, NA, NA, 1650, 275
), transect_number = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source