MLnewby
MLnewby

Reputation: 139

R: Function does not give data frame as output

To calculate differences between values from two data frames, I merged the data frames and then performed my calculations. First, I did this step-by-step:

B2_1 <- merge(2_1G, G, by = "G", all = TRUE)
B2_1$result <- B2_1$freq.x - B2_1$freq.y
B2_1$percentage <- (B2_1$result/B2_1$freq.y)*100

This gave the output I want, as one data frame:

View(B2_1)

Gender  freq.x  freq.y  result  percentage
1       39600   39542   58      0.15
2       41652   41710   -58     -0.14

However, I have to do this for a lot of data frames, so I wanted to be more concise. So, I wrote this function:

B <- function(frame1, frame2, column, bframe){
 bframe <- merge(frame 1, frame2, by = column, all = TRUE)
 bframe$result <- bframe$freq.x - bframe$freq.y
 bframe$percentage <- (bframe$result/bframe$freq.y)*100
}

B(DT2_1, 2_1, "Gender", BDT_2_1) 

If I run the first code, the calculations are put in the created/desired data frame (see example). If I run the function (and the call) then it does nothing. What am I doing wrong?

Upvotes: 0

Views: 374

Answers (1)

PinkFluffyUnicorn
PinkFluffyUnicorn

Reputation: 1316

Right now you only modify the value of bframe without stating that the function should return an outcome. Adding a return statement (the result that your function should provide) should solve your problem.

B <- function(frame1, frame2, column) {
   ....
   return(bframe)
}

bframe <- B(...)

Additional information on how to define functions in R can be found here

Upvotes: 2

Related Questions