Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr rename not working with regular expression

Tags:

r

dplyr

The select function works fine when I try to rename variables according to certain conditions

require(dplyr)
select(iris, petal = starts_with("Petal"))

However when I try to keep all the other variables using

rename(iris, petal = starts_with("Petal"))

Error: Arguments to rename must be unquoted variable names. Arguments petal are not.

I have no idea why dplyr complains about this. If this behavior is intended, what is the right way to rename variables using starts_with (or contains) while keeping other variables there?

like image 481
Yifei Avatar asked May 29 '15 12:05

Yifei


People also ask

How do I rename my dplyr?

dplyr rename column rename() function from dplyr takes a syntax rename(new_column_name = old_column_name) to change the column from old to a new name. The following example renames the column from id to c1 . The operator – %>% is used to load the renamed column names to the data frame.

How do I rename multiple columns in dplyr?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I rename a variable in R studio?

To rename an object or variable in R, just copy the data. frame variable to another variable by using the assignment operator (<- or =) and remove the existing variable using rm() function.

How do I rename a column in R studio?

Rename Column using colnames() colnames() is the method available in R base which is used to rename columns/variables present in the data frame. By using this you can rename a column by index and name. Alternatively, you can also use name() method.


1 Answers

select is already renaming them for you. You can add everything() to the call in order to get the rest of the columns

select(iris, petal = starts_with("Petal"), everything())
#     petal1 petal2 Sepal.Length Sepal.Width    Species
# 1      1.4    0.2          5.1         3.5     setosa
# 2      1.4    0.2          4.9         3.0     setosa
# 3      1.3    0.2          4.7         3.2     setosa
# 4      1.5    0.2          4.6         3.1     setosa
# 5      1.4    0.2          5.0         3.6     setosa
# 6      1.7    0.4          5.4         3.9     setosa
# 7      1.4    0.3          4.6         3.4     setosa
# 8      1.5    0.2          5.0         3.4     setosa
# 9      1.4    0.2          4.4         2.9     setosa
...
like image 110
David Arenburg Avatar answered Oct 01 '22 08:10

David Arenburg