Skip to content

Looking for an easy way to change the names of a vector

3 messages · Christofer Bogaso, Rui Barradas, arun

#
Hello again,

Let say I have following vector (this is basically a snap of very large vector):


Data <- 1:8
names(Data) <- c("ada", "fsdfs", "asd fd", "asdsa", "dsada", "asasad",
"adas asdad", "aasaa")
Data

Now I want to change the names according to following rule:

1. If there is any space then replace that space by "-"
2. Otherwise add "-XXX" at the last to each name

Therefore the names will be:

c("ada-XXX", "fsdfs-XXX", "asd-fd", "asdsa-XXX", "dsada-XXX",
"asasad-XXX", "adas-asdad", "aasaa-XXX")


Can somebody point me some direct way for that?

Thanks for your help
#
Hello,

Use ifelse, and assign its values to names(Data)


ifelse(grepl(" ", names(Data)), gsub(" ", "-", names(Data)), 
paste0(names(Data), "-XXX"))


Hope this helps,

Rui Barradas
Em 14-02-2013 11:43, Christofer Bogaso escreveu:
#
Hi, 

names(Data)[-grep(".*\\s+.*",names(Data))]<-paste(names(Data)[-grep(".*\\s+.*",names(Data))],"-XXX",sep="")
names(Data)[grep(".*\\s+.*",names(Data))]<-gsub("[ ]","-",names(Data)[grep(".*\\s+.*",names(Data))])
?names(Data)
#[1] "ada-XXX"??? "fsdfs-XXX"? "asd-fd"???? "asdsa-XXX"? "dsada-XXX" 
#[6] "asasad-XXX" "adas-asdad" "aasaa-XXX" 

A.K.

----- Original Message -----
From: Christofer Bogaso <bogaso.christofer at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Thursday, February 14, 2013 6:43 AM
Subject: [R] Looking for an easy way to change the names of a vector

Hello again,

Let say I have following vector (this is basically a snap of very large vector):


Data <- 1:8
names(Data) <- c("ada", "fsdfs", "asd fd", "asdsa", "dsada", "asasad",
"adas asdad", "aasaa")
Data

Now I want to change the names according to following rule:

1. If there is any space then replace that space by "-"
2. Otherwise add "-XXX" at the last to each name

Therefore the names will be:

c("ada-XXX", "fsdfs-XXX", "asd-fd", "asdsa-XXX", "dsada-XXX",
"asasad-XXX", "adas-asdad", "aasaa-XXX")


Can somebody point me some direct way for that?

Thanks for your help

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.