Jeromy Anglim
Jeromy Anglim

Reputation: 34947

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

Upvotes: 0

Views: 194

Answers (2)

Nikolay Skryabin
Nikolay Skryabin

Reputation: 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

Upvotes: 0

Dason
Dason

Reputation: 61973

I don't think there is a way to do this without manually adding those line numbers in yourself. It's not too bad to do though.

line_num_cat <- function(x){
  tmp <- unlist(strsplit(x, "\n"))
  cat(paste0(seq_len(length(tmp)), ": ", tmp, collapse = "\n"), "\n")
}

x <- "A\nB\nC"
line_num_cat(x)

which gives

> line_num_cat(x)
1: A
2: B
3: C

Upvotes: 4

Related Questions