'How to print line numbers for a multi-line character variable in R?

I'm trying to identify line numbers in a JAGS script stored in a scalar character variable. I want to add line numbers to cat output in R.

To simplify the example, if I had a string:

x <- "A\nB\nC"

and I do cat(x), I get:

A
B
C

How can I print line numbers with the string. I.e., to display something like:

1: A
2: B
3: C
r


Solution 1:[1]

This works too:

x <- "A\nB\nC"

list_x <- strsplit(x,"\n")

cat(paste0(1:length(list_x[[1]]), ": ", list_x[[1]]), sep="\n")

the result:

1: A
2: B
3: C

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1