我有一个类似于下面的字符串

my_string <- "apple,banana,orange,"

我想除以,来产生输出:

list(c('apple', 'banana', 'orange', ""))

我认为strplit可以做到这一点,但它将拖尾视为不存在

my_string <- "apple,banana,orange,"

strsplit(my_string, split = ',')
#> [[1]]
#> [1] "apple"  "banana" "orange"

reprex package(v2.0.1)于2023-11-15创建

实现所需输出的最简单方法是什么?

带有示例字符串和所需输出的更多测试用例

string1 = "apple,banana,orange,"
output1 = list(c('apple', 'banana', 'orange', ''))

string2 =  "apple,banana,orange,pear"
output2 = list(c('apple', 'banana', 'orange', 'pear'))

string3 =  ",apple,banana,orange"
output3 = list(c('', 'apple', 'banana', 'orange'))

## Examples of non-comma separated strings
# '|' separator
string4 =  "|apple|banana|orange|"
output4 = list(c('', 'apple', 'banana', 'orange', ''))

# 'x' separator
string5 =  "xapplexbananaxorangex"
output5 = list(c('', 'apple', 'banana', 'orange', ''))

编辑:

理想情况下,解决方案应适用于任何分裂角色

我也更喜欢BASE-R解决方案(尽管仍然要链接任何提供此功能的包,因为它们的源代码可能有助于查看!)

推荐答案

Pasting another separator at the end should allow strsplit to function as intended.
Otherwise, you could fall back to using the scan function, which underpins the read.csv/table functions:

strsplit(paste0(string1, ","), ",")
##[[1]]
##[1] "apple"  "banana" "orange" ""

一般考虑regex替换:

L <- list(string1, string2, string3, string4, string5)
mapply(
    function(x,s) strsplit(paste0(x, gsub("\\\\", "", s)), split=s),
    L,
    c(",", ",", ",", "\\|", "x")
)

##[[1]]
##[1] "apple"  "banana" "orange" ""      
##
##[[2]]
##[1] "apple"  "banana" "orange" "pear"  
##
##[[3]]
##[1] ""       "apple"  "banana" "orange"
##
##[[4]]
##[1] ""       "apple"  "banana" "orange" ""      
##
##[[5]]
##[1] ""       "apple"  "banana" "orange" "" 

scan选项:

scan(text=string1, sep=",", what="")
##Read 4 items
##[1] "apple"  "banana" "orange" ""

概括地说:

mapply(
    function(x,s) scan(text=x, sep=s, what=""),
    L,
    c(",", ",", ",", "|", "x")
)

R相关问答推荐

确定邻国

如何计算新变量中的通货inflating 率?

通过R访问MoveApps API

过滤Expand.Grid的结果

将一个载体的值相加,直到达到另一个载体的值

在ggplot Likert条中添加水平线

pickerInput用于显示一条或多条geom_hline,这些线在图中具有不同 colored颜色

格点中指数、双曲和反双曲模型曲线的正确绘制

在"gt"表中添加第二个"groupname_col",而不连接列值

筛选出以特定顺序患病的个体

使用geom_segment()对y轴排序

将包含卷的底部25%的组拆分为2行

解析R函数中的变量时出现的问题

如何将一列中的值拆分到R中各自的列中

有没有办法一次粘贴所有列

将工作目录子文件夹中的文件批量重命名为顺序

为什么函数toTitleCase不能处理english(1),而toupper可以?

需要一个函数来在第一行创建一个新变量,然后用新变量替换一个不同的变量(对于多行)

如何获取R chromote中的当前URL?

具有自定义仓位限制和计数的GGPLATE直方图