0

I am trying to loop and rename colnames in a data frame.

How can I embed a numeric variable in the R's colname string. I found the .(x) associated to the bquote/paste method for title in graphics but it doesn't work with a standard string.

In Ruby I can embed a variable in a string using #{x} in the following way

irb(main):005:0> (1..10).each{|i| p "hello no #{i}"}
"hello no 1"
"hello no 2"
"hello no 3"
"hello no 4"
"hello no 5"
"hello no 6"
"hello no 7"
"hello no 8"
"hello no 9"
"hello no 10"

Thanks

3
  • paste? There is also sprintf but that's probably overkill. Commented Jun 6, 2012 at 11:51
  • Thanks, actually paste() works fine.I just messed up with .(x) instead of using a paste(name,num) Commented Jun 6, 2012 at 12:05
  • Both paste and sprintf are vectorized, so you might not even need the loop. Commented Jun 6, 2012 at 15:59

1 Answer 1

1

You can simply use sprintf(). For example:

i <- 4;
data[[sprintf("hello.%1.2d",i)]] <- ...;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.