0

I am trying to get these lists:

dim_29 <- list(c(114.49337,  20.29176, 390.74801, 592.75864))
dim_30 <- list(c(112.39257,  19.24136, 388.64721, 594.85944))
dim_31 <- list(c(112.39257,  19.24136, 402.30239, 589.60745))
dim_28 <- list(c(113.44297,  19.24136, 374.99204, 587.50665)) 

To do this:

> dim_28 <- unlist(dim_28)
> dim_28
[1] 113.44297  19.24136 374.99204 587.50665
> dim_28 <- paste(dim_28, sep = " ", collapse = ", ")
> dim_28
[1] "113.44297, 19.24136, 374.99204, 587.50665"

by using a loop or some other way to automate the process with all the lists. What loop would I have to write to accomplish this or should I be using a differnet function? Any help would be great, thanks!

1
  • with the lapply/apply/sapply family of functions, or newer libraries like purrr. This is a duplicate. Also, if you have a regularly-named and -indexed set of vectors of the same length, why not just use a matrix, and index into its n'th row? Much more performant than lists.
    – smci
    Commented Apr 26, 2019 at 0:25

3 Answers 3

3

Looping is easy if your data structure is right. You have 4 sequentially named lists. Each list contains a single vector. Instead, you should have 1 list, containing 4 vectors:

dim_list = list(
  d29 = c(114.49337,  20.29176, 390.74801, 592.75864),
  d30 = c(112.39257,  19.24136, 388.64721, 594.85944),
  d31 = c(112.39257,  19.24136, 402.30239, 589.60745),
  d28 = c(113.44297,  19.24136, 374.99204, 587.50665)
)

lapply(dim_list, paste, collapse = ", ")
# $d29
# [1] "114.49337, 20.29176, 390.74801, 592.75864"
# 
# $d30
# [1] "112.39257, 19.24136, 388.64721, 594.85944"
# 
# $d31
# [1] "112.39257, 19.24136, 402.30239, 589.60745"
# 
# $d28
# [1] "113.44297, 19.24136, 374.99204, 587.50665"
1
  • 1
    or more compactly lapply(dim_list, toString) purrr::map(dim_list, toString)
    – akrun
    Commented Apr 26, 2019 at 2:43
0

This is one way I came up with.

dim_29 <- list(c(114.49337,  20.29176, 390.74801, 592.75864))
dim_30 <- list(c(112.39257,  19.24136, 388.64721, 594.85944))
dim_31 <- list(c(112.39257,  19.24136, 402.30239, 589.60745))
dim_28 <- list(c(113.44297,  19.24136, 374.99204, 587.50665)) 

list_group = list(dim_28, dim_29, dim_30, dim_31)
output_dat = list()
for (i in 1:4){
  dat =list_group[[i]][[1]]
  output_dat[i] = paste0(dat, sep = " ", collapse = ", ")
}

I hope you find this helpful.

0
> lapply(mget(ls(pattern = "^dim_\\d+")), function(x) paste(unlist(x), sep = " ", collapse = ", "))
$`dim_28`
[1] "113.44297, 19.24136, 374.99204, 587.50665"

$dim_29
[1] "114.49337, 20.29176, 390.74801, 592.75864"

$dim_30
[1] "112.39257, 19.24136, 388.64721, 594.85944"

$dim_31
[1] "112.39257, 19.24136, 402.30239, 589.60745"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.