使用lapply执行元素比较的自定义函数

时间:2018-03-04 19:01:28

标签: r list apply lapply

我正在尝试寻找一种更多R方式来应用我的函数,将两个字符串一起比较到命名列表中的命名列表元素。寻找一种方法来做这个没有for循环,所以我看了lapply;任何我非常感谢的建议!

这是一个可重复的例子:

my_list <- list(coca = c(13, 422, 131, 2), cola = c(11, 53, 3))
names(my_list$coca) <- c("sprite", "coke", "pepsi", "cocacoca")
names(my_list$cola) <- c("lemonade", "juice", "colacola")

compare_substr <- function(word1, word2, min_char){

 # INPUT: word1, word2, and min_char (optional)
 # OUTPUT: TRUE or FALSE

 if(class(word1) != "character" || class(word2) != "character"){
   stop("Error: Words being compared are not in character format")
 }
 if(missing(min_char)){
   min_char <- nchar(word1)
 }
 if(substring(word1, 1, min_char) == substring(word2, 1, min_char)){
   return(TRUE)
 }
 else{
   return(FALSE)
 }
}

最终结果应如下所示,以便我可以对那些显示TRUE

的内容进行过滤
$coca
sprite     coke    pepsi cocacoca 
FALSE    FALSE    FALSE     TRUE 

$cola
lemonade    juice colacola 
FALSE    FALSE     TRUE 

我目前的方法是通过for循环,但我知道有一个更清洁的方式来做这个lapply,但我开始认为我的compare_substr函数必须改为做所以...有没有办法在不改变功能的情况下实现这一目标?

谢谢!

1 个答案:

答案 0 :(得分:0)

方法1:这是使用sapply函数:

说明:

1 - 对于my_list中的每个名称,grepl函数检查名称是否存在于子列表名称中。 grepl返回一个布尔值。
2 - 我们在新plist中保存上一步的输出。
3 - 最后,我们设置名称。

# create a new list
library(stringr)
plist <- list()

# match names and update the new list
plist <- sapply(names(my_list), function(x) {

    plist[[x]] <- grepl(x, names(my_list[[x]]))


}) 

# set names
names(plist$coca) <- c("sprite", "coke", "pepsi", "cocacoca")
names(plist$cola) <- c("lemonade", "juice", "colacola")

# output
    $coca
  sprite     coke    pepsi cocacoca 
   FALSE    FALSE    FALSE     TRUE 

$cola
lemonade    juice colacola 
   FALSE    FALSE     TRUE 

方法2:此外,你可以使用for循环这样做(很高兴知道):

library(stringr)
new_list <- list()
for(i in names(my_list))
{

    # get name of the sublist
    temp <- names(my_list[[i]])

    # check if the name of parent list is present (this returns boolean)
    sol <- str_detect(temp, i)

    # update new list
    new_list[[i]] <- sol
    names(new_list[[i]]) <- temp

}

print(new_list)

$coca
  sprite     coke    pepsi cocacoca 
   FALSE    FALSE    FALSE     TRUE 

$cola
lemonade    juice colacola 
   FALSE    FALSE     TRUE