Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename columns using function input in dplyr

Tags:

r

dplyr

I know there are many similar questions regarding renaming columns in R, but I still have not found an elegant way to achieve this simple task, which can be easily done in Python.

Here is a simple function to convert GIS dataframe into Spatial Points. But first I want to rename coordinate columns into "lon" and "lat". Some data labels them "X" and "Y", while other may call "long" and "lat". So I want users to specify what were column names for "lon" and "lat". I am using dplyr. However, following will not work.

library("magrittr")
library("tidyverse")
ToSpatialPoint <- function(data, lon_col="long",lat_col="lati"){
    data %<>% rename(lon=lon_col,lat=lat_col) %<>% distinct(lon,lat) %<>% filter(!is.na(lon),!is.na(lat))
    processed_pts <- SpatialPoints(coords=cbind(lon=data$lon,lat=data$lat), proj4string = CRS("+init=epsg:4326"))
    return(processed_pts)
}

I receive this error:

Error: `lon_col`, `lat_col` contains unknown variables 
like image 230
Lala La Avatar asked Oct 28 '25 12:10

Lala La


2 Answers

The accepted answer didn't work for me, but luckily I remembered the "Assignment by reference" operator, which is:

:=

-->

rename(new_variable_name := old_variable_name)

The package data.table has good documentation about it in this vignette.

In dplyr you will have to wrap the variable name you are passing with sym and !! (help on !! is under ??rlang::quotation). Your new rename function should look like:

data %>%
  rename(!!sym(lon_col) := lon,
         !!sym(lat_col) := lat)
like image 163
MiamiCG Avatar answered Oct 30 '25 02:10

MiamiCG


Finally, I figured out the answer myself thanks to a link shared by my awesome roommate. This document from tidyverse.org explains how to program with dplyr. In particular, how to take function inputs and evaluate them in dplyr.

Following is the code that will work:

ToSpatialPoint <- function(data,lon_col="long",lat_col="lati"){
  lon_col <- enquo(lon_col)
  lat_col <- enquo(lat_col)
  data <– data %>% rename(lon=!!lon_col,lat=!!lat_col)
  return(data)
}
like image 32
Lala La Avatar answered Oct 30 '25 02:10

Lala La



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!