Vinay
Vinay

Reputation: 477

Rename elements of character variable

I need to suffix the elements in a character variable (a) with extension .TXT. The following code appears to works well (as it renames all the elements on terminal), but when I type the name of other variable (A) (which stores the modified names), only last element gets printed.

for(i in 1:length(a))
{
A<- paste (a[i],".TXT",sep="") 
print (A)
}

Any suggestions please.

Upvotes: 0

Views: 732

Answers (3)

akrun
akrun

Reputation: 887148

Not sure why you need a loop for this:

a <- LETTERS[1:5]
A <- paste0(a, ".TXT")
A
#[1] "A.TXT" "B.TXT" "C.TXT" "D.TXT" "E.TXT"

Upvotes: 4

user3710546
user3710546

Reputation:

This one should work:

A <- as.character()
for(i in 1:length(a)){
  A[i] <- paste(a[i],".TXT",sep="")
}
A

Upvotes: 1

Math
Math

Reputation: 2436

This loop overwrites A at every iteration. What you want is A to be a vector, try that :

A = c()
for(i in 1:length(a)){
  A <- c( A, paste (a[i],".TXT",sep="") )
  print (A[i])
}

It creates A as an empty vector of length 0, then extends it with the modified elements of a.

Upvotes: 2

Related Questions