将列表列表转换为字符向量 [英] Convert a list of lists to a character vector

查看:115
本文介绍了将列表列表转换为字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符列表。例如:

I have a list of lists of characters. For example:

l <- list(list("A"),list("B"),list("C","D"))

所以您可以看到某些元素的长度大于1 。

So as you can see some elements are lists of length > 1.

我想将此列表列表转换为字符向量,但是我希望长度大于1的列表在字符向量中作为单个元素出现。

I want to convert this list of lists to a character vector, but I'd like the lists with length > 1 to appear as a single element in the character vector.

取消列表函数不能实现此目的,而是:

the unlist function does not achieve that but rather:

> unlist(l)
[1] "A" "B" "C" "D"

有没有比以下更快的东西了?

Is there anything faster than:

sapply(l,function(x) paste(unlist(x),collapse=""))

要获得我想要的结果:

"A"  "B"  "CD"


推荐答案

您可以跳过取消列出的步骤。您已经发现 paste0 需要 collapse = TRUE 才能将向量的顺序元素绑定在一起:

You can skip the unlist step. You already figured out that paste0 needs collapse = TRUE to "bind" sequential elements of a vector together:

> sapply( l, paste0, collapse="")
[1] "A"  "B"  "CD"

这篇关于将列表列表转换为字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆