编写循环以一次在多个列表上执行

时间:2019-04-25 23:35:26

标签: r vectorization

我正在尝试获取以下列表:

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)) 

为此:

> 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"

通过使用循环或其他方式自动处理所有列表。我必须写哪个循环来完成此操作,或者应该使用Differentnet函数? 任何帮助都会很棒,谢谢!

3 个答案:

答案 0 :(得分:3)

如果您的数据结构正确,则循环很容易。您有4个顺序命名的列表。每个列表包含一个向量。相反,您应该有1个列表,其中包含4个向量:

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 :(得分:0)

这是我想出的一种方式。

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 = ", ")
}

希望您对此有帮助。

答案 2 :(得分: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"