Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use outside variable inside of rename() function in R

Tags:

r

I'm new to R and have a problem

I am trying to reformat some data, and in the process I would like to rename the columns of the new data set.

here is how I have tried to do this:

first the .csv file is read in, lets say case1_case2.csv then the name of the .csv file is broken up into two parts each part is assigned to a vector so it ends up being like this:

xName=case1
yName=case2

After I have put my data into new columns I would like to rename each column to be case1 and case2

to do this I tried using the rename function in R but instead of renaming to case1 and case2 the columns get renamed to xName and yName.

here is my code:

  for ( n in 1:length(dirNames) ){
      inFile <- read.csv(dirNames[n], header=TRUE, fileEncoding="UTF-8-BOM")
      xName <- sub("_.*","",dirNames[n])
      yName <- sub(".*[_]([^.]+)[.].*", "\\1", dirNames[n])
      xValues <- inFile %>% select(which(str_detect(names(inFile), xName))) %>% stack() %>% rename( xName = values ) %>% subset( select = xName)
      yValues <- inFile %>% select(which(!str_detect(names(inFile), xName))) %>% stack() %>% rename(yName = values, Organisms=ind)
      finalForm <- cbind(xValues, yValues) %>% filter(complete.cases(.))

}

how can I make sure that the variables xName and yName are expanded inside of the rename() function

thanks.

like image 380
Sam Avatar asked Sep 08 '25 02:09

Sam


1 Answers

You didn't provide a reproducible example, so I'll just demonstrate the idea in general. The rename function is part of the dplyr package.

You need to "unquote" the variable that contains the string you want to use as the new column name. The unquote operator is !! and you'll need to use the special := assignment operator to make unquoting on the left hand side allowed.

library(tidyverse)
df <- data_frame(x = 1:3)
y <- "Foo"

df %>% rename(y=x)      # Not what you want - need to unquote y
df %>% rename(!!y = x)  # Gives error - need to use :=
df %>% rename(!!y := x) # Correct
like image 194
ngm Avatar answered Sep 10 '25 08:09

ngm