Home > Net >  Print list in specific format
Print list in specific format

Time:11-29

I have a list with 72 bounding boxes. This is the dput (just 5 of them).

list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178
), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007
), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007
), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007
), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007
))

and this is the desired output:

c(7.4267580,47.3983490,7.8508356,47.6861780)

How can I print each bounding box in the desired output using a for loop?

CodePudding user response:

You'll get this output by running

dput(lapply(your_list, unname))

However, if you want to save the stringified vectors to a new vector, there’s a more direct way, via the toString function. first off, here’s what toString does to a vector:

toString(1 : 5)
# [1] "1, 2, 3, 4, 5"

Great! That’s almost what we want; we just need to put it into c(…):

paste0('c(', toString(1 : 5), ')')
# [1] "c(1, 2, 3, 4, 5)"

And now we need to apply this operation to every element in the original list. vapply does that:

result = vapply(your_list, \(x) paste0('c(', toString(x), ')'), character(1L))

CodePudding user response:

The following will print each element of the list in the required format:

have <- list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178
), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007
), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007
), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007
), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007
))

for (item in have) {dput(unname(item))}
  • Related