Display order of objects in vector in R

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Display order of objects in vector in R



Let's say I create a simple vector:



x <- seq(1, 50, by = 5)


x <- seq(1, 50, by = 5)



Then I might want to display its contents to see which item is the 7th:


print(x)

[1] 1 6 11 16 21 26 31 36 41 46



Is there a simple way to display the contents such that each item is numbered?



[1] 1, [2] 6, [3] 11, etc.


[1] 1, [2] 6, [3] 11, etc.




3 Answers
3



One simple option is to column-bind a counter next to the original vector:


cbind(1:length(x), x)



An elegant way might be to use ?names.


?names


x <- seq(1, 50, by = 5)
names(x) <- seq_along(x)
x
1 2 3 4 5 6 7 8 9 10
1 6 11 16 21 26 31 36 41 46



I assume you're asking how to modify print to include the index of every element of a vector x.


print


x



Here is a possibility


x <- seq(1, 50, by = 5)

cat(sapply(seq_along(x), function(i) (sprintf("[%i] %i", i, x[i]))), "n")
#[1] 1 [2] 6 [3] 11 [4] 16 [5] 21 [6] 26 [7] 31 [8] 36 [9] 41 [10] 46



Or you could define a custom my.print function that nicely wraps lines every nmaxth entry for long vectors


my.print


nmax


my.print <- function(x, nmax = 6) {
os <- 0
while (length(x) > 0) {
cat(sapply(seq_along(x[1:min(length(x), 6)]), function(i)
sprintf("[%i] %i", i + os, x[i])), "n")
x <- x[-(1:min(length(x), nmax))]
os <- os + nmax
}}

my.print(x)
#[1] 1 [2] 6 [3] 11 [4] 16 [5] 21 [6] 26
#[7] 31 [8] 36 [9] 41 [10] 46






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP