Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用lappy连接列表元素_R_Lapply - Fatal编程技术网

R 使用lappy连接列表元素

R 使用lappy连接列表元素,r,lapply,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) 并返回此结果: [1] "

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

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)
并返回此结果:

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

谢谢!顺便问一下,
lappy
是否有跳过空列表项的选项?电话号码中的第二个列表项为空。我现在已经解决了预处理问题:
电话号码列表0]
@Bobby你可以使用
过滤器
,即
过滤器(长度、电话号码列表)
我不完全理解
过滤器
。也许这会帮助我了解如何使用它来获取长度大于1的列表元素。@Bobby它会过滤长度不为0的列表元素。或者创建一个长度为
的逻辑表达式
长度(电话号码列表)>0
lapply( phone_numbers_list,
str_c(
  "(",
  phone_numbers[,2],
  ")",
  " ",
  phone_numbers[,3],
  "-",
  phone_numbers[,4])
  )
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"