0
votes

This should be a very straight forward code, I'm just trying to bind new variables to an existing dataframe. However, dplyr mutate doesn't seem to work within a function. When I call the function, addLocation, the items are not added.

Location data (df.russia_locations)

 location    lon         lat
 Kalingrad  20.45221    54.71043        
  Moscow    37.61730    55.75583    

Bind to itemTest (could be any dataset)

     addLocation <- function(itemInfo){ itemInfo <- mutate(itemInfo,
                                     Kalingrad_lon = df.russia_locations[1,2],
                                     Kalingrad_lat = df.russia_locations[1,3],
                                     Moscow_lon = df.russia_locations[2,2],
                                     Moscow_lat = df.russia_locations[2,3]
                                    )}
     addLocation(itemTest)

I must be missing something?

1
@RonakShah that is the location dataframelydias

1 Answers

1
votes

You need to add return(itemInfo) before your last bracket in your function or remove the itemInfo <- assignment in your function. If you assign the output of your function to a name, you get the expected printed output.

> itemTest2 <- addLocation(itemTest)
> length(addLocation(itemTest))
[1] 5
> length(addLocation(itemTest))==length(itemTest)
[1] FALSE