colnames() function

16 views
Skip to first unread message

Ayala Allon

unread,
Aug 13, 2014, 5:34:43 AM8/13/14
to israel-r-...@googlegroups.com
Hi,

I wanted to ask if there is a way to use the colnmaes() function by providing the name of the column I want? and not by providing the index of the column?

For example I have

 z<- data.frame(x=1:10,y=11:20)
> z
    x  y
1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20

If I want to replace the name of the first column I'll do:

> colnames(z)[1]<-"new.name"
> z
   new.name  y
1         1 11
2         2 12
3         3 13
4         4 14
5         5 15
6         6 16
7         7 17
8         8 18
9         9 19
10       10 20

But how can I replace the name if I don't know (or don't want to find out) the index of the column for which I want to set the new name? 
For example if I want now to replace the name "new.name" to "xxx" by providing the name of the column (i.e., "new.name") and by providing the its index (i.e., z[1]). I tried for example 
colnames(z)[["new.name"]]<- "xxx"
but I get an error.

Any ideas? I have an idea how to pass it but I was wondering if there is a way to do it using colnames()
Thanks
Ayala

Jonathan Rosenblatt

unread,
Aug 13, 2014, 6:11:39 AM8/13/14
to israel-r-user-group
One possibility:
names(z)[names(z) %in% 'x'] <- 'q'




Ayala

--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-g...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Jonathan Rosenblatt
www.john-ros.com

amit gal

unread,
Aug 13, 2014, 6:20:12 AM8/13/14
to israel-r-...@googlegroups.com
or use match()

דוד ארנבורג

unread,
Aug 14, 2014, 8:13:36 AM8/14/14
to israel-r-...@googlegroups.com
Or 

colnames(z)[grepl("new.name", colnames(z))] <- "xxx"

Jonathan Rosenblatt

unread,
Aug 14, 2014, 8:40:32 AM8/14/14
to israel-r-user-group
indeed
grepl also has the advantage of taking regular expressions.


--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-g...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Jonathan Rosenblatt
www.john-ros.com

Ayala Allon

unread,
Aug 15, 2014, 4:40:33 AM8/15/14
to israel-r-...@googlegroups.com
Thank you all for the suggestions!
Best
Ayala
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-group+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Jonathan Rosenblatt
www.john-ros.com

Reply all
Reply to author
Forward
0 new messages