gpt4 book ai didi

R strsplit 保留最后一个空元素为空字符串

转载 作者:行者123 更新时间:2023-12-04 13:40:18 25 4
gpt4 key购买 nike

R的strsplit如果为“空”(示例 2),则删除最后一个元素,但不会在第一个元素(示例 3)或在要拆分的向量中间(示例 4)时删除。

> unlist(strsplit(x = "1,4", split = ",")) #Example 1
[1] "1" "4"
> unlist(strsplit(x = ",4", split = ",")) #Example 2
[1] "" "4"
> unlist(strsplit(x = "1,", split = ",")) #Example 3
[1] "1"
> unlist(strsplit(x = "1,,,4", split = ",")) #Example 4
[1] "1" "" "" "4"

有没有办法解析字符串,如果 split 后为空,则允许保留最后一个元素:
> strmagic(x = "1,", split = ",") #strmagic being the wanted function
[1] "1" ""

其他软件包的解决方案是 here (似乎)。可以在基础 R 中完成吗?

更新

是否需要添加填充元素,然后是 la:
strmagic <- function(v, sep)lapply(v, function(x)head(unlist(strsplit(paste(x, "-", sep = sep), split = sep)), -1))

最佳答案

奇怪的。这有效,但不是最有效的。 ZAQ 只是一组随机字符

sp <- function( X ){
X <- paste0( X, "ZAQ" )
X <- unlist(strsplit(x = X, split = ","))
X <- gsub( "ZAQ" ,"" ,X)
X
}
sp("1,4")
sp(",4")
sp("1,")
sp("1,,,4")

关于R strsplit 保留最后一个空元素为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58187238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com