[R] text replacement with a loop in a script file

Rui Barradas ruipbarradas at sapo.pt
Fri May 4 16:43:19 CEST 2012


Hello,


diegogiri wrote
> 
> Hi, i'm a new r user and I will take you a simple (not for me)question.
> I have a r script file like this:
> 
> text <- c("<ARCHIVIO>                         <name> <definition>")
> 
> I have a csv file like:
> NAME
> alfa
> beta 
> gamma
> 
> how can I replace with a loop statment metadata "<name>" of script file
> with the values names in the csv file?
> I need have all in a single script file.
> thanks a lot for all type of suggestions.
> bye
> diegogiri
> 

Try

text <- c("<ARCHIVIO>                         <name> <definition>")

# I have a csv file like:
x <- read.csv(text="
NAME
alfa
beta
gamma
", header=TRUE, stringsAsFactors=FALSE)

pattern <- paste("<", names(x), ">", sep="")
sapply(unlist(x), function(y) sub(pattern, y, text, ignore.case=TRUE))

When you read the csv file from disk, don't forget setting the
stringsAsFactors option to FALSE.

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/text-replacement-with-a-loop-in-a-script-file-tp4608744p4608798.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list