如何从单个项目列表中删除未命名的元素? [英] How to remove an unnamed element from a single item list?

查看:54
本文介绍了如何从单个项目列表中删除未命名的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来可能是一个非常初学者的问题,也可能是一个非常基本而又愚蠢的问题,但不知何故我对此感到头疼.

This may sound a very beginner's question and very well it could also be a very basic and stupid question, but somehow I am having headache in doing it.

假设我有一个物品清单

v <- as.list("1, 2, 3,")

v
[[1]]
[1] "1, 2, 3,"

现在我想将其所有项目拆分为单独的项目

Now I want to split all of its items as separate items

v2 <- lapply(str_split(v, pattern = ","), trimws)
v2
[[1]]
[1] "1" "2" "3" "" 

现在我要不使用 [] 从列表的第一项也是唯一的项中删除此" 吗?

Now I want to remove this "" from the first and only item of this list without using []?

推荐答案

使用 nzchar .

lapply(v2, function(x) x[nzchar(x)])
# [[1]]
# [1] "1" "2" "3"

或首先使用似乎似乎更复杂的 base :: strsplit .

Or use base::strsplit in the first place which appears to be more sophisticated.

lapply(strsplit(v[[1]], ","), trimws)
# [[1]]
# [1] "1" "2" "3"

这篇关于如何从单个项目列表中删除未命名的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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