使用lapply连接列表元素

时间:2018-05-20 14:04:13

标签: r lapply

问题如下。首先是一个工作实例:

library(stringr)
library(rebus)

phone_numbers_mat <- structure(c("555-555-0191", NA, "555) 555 0191", "555.555.0191", 
"555", NA, "555", "555", "555", NA, "555", "555", "0191", NA, 
"0191", "0191"), .Dim = c(4L, 4L)

以下代码重新构建上述矩阵中的电话号码:

str_c(
  "(",
  phone_numbers_mat[,2],
  ")",
  " ",
  phone_numbers_mat[,3],
  "-",
  phone_numbers_mat[,4] )

并返回此结果:

[1] "(555) 555-0191" NA               "(555) 555-0191" "(555) 555-0191"

但是当我尝试使用列表结构执行类似的操作时,我收到错误“错误:维度数量不正确”

phone_numbers_list <- list(structure(c("555-555-0191", "555", "555", "0191"), .Dim = c(1L, 
4L)), structure(character(0), .Dim = c(0L, 4L)), structure(c("555) 555 0191", 
"555", "555", "0191"), .Dim = c(1L, 4L)), structure(c("555.555.0191", 
"555.555.0192", "555", "555", "555", "555", "0191", "0192"), .Dim = c(2L, 
4L)))

我的尝试(返回上面的错误):

lapply( phone_numbers_list,
str_c(
  "(",
  phone_numbers[,2],
  ")",
  " ",
  phone_numbers[,3],
  "-",
  phone_numbers[,4])
  )

如何正确处理列表以重新构建电话号码?

1 个答案:

答案 0 :(得分:1)

我们需要一个匿名函数调用

lapply(phone_numbers_list, function(phone_numbers) str_c(
   "(",
   phone_numbers[,2],
    ")",
    " ",
   phone_numbers[,3],
    "-",
   phone_numbers[,4])
  )
#[[1]]
#[1] "(555) 555-0191"

#[[2]]
#[1] "() -"

#[[3]]
#[1] "(555) 555-0191"

#[[4]]
#[1] "(555) 555-0191" "(555) 555-0192"