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"