R 给出奇怪的警告"the condition has length > 1 and only the first element will be used"



我试图在R中编写以下函数:它将从包含逗号分隔部分的字符串构造修剪字符串部分的向量。

# parse string into vector of trimmed comma-separated parts
parseLine<-function(str)
{
    inputVector = strsplit(str, ",")
    outputVector = c()
    for(s in inputVector)
    {
        s = gsub("^\s+|\s+$", "", s)
        if(nchar(s) > 0)
            outputVector = c(outputVector, s)
    }
    return(outputVector)
}

这个函数定义被成功解析。但是当我像这样执行它时:

parseLine("a,   b, c, d")

我得到结果,但也有一个奇怪的警告:

[1] "a" "b" "c" "d"
Warning message:
In if (nchar(s) > 0) outputVector = c(outputVector, s) :
  the condition has length > 1 and only the first element will be used

我的问题是:

  • 这是什么意思?
  • 我怎么做才能摆脱它?

更新:我找到了正确的解决方案。问题是strsplit()给出一个列表作为它的输出。

# parse string into vector of trimmed comma-separated parts
parseLine<-function(str)
{
    inputVector = strsplit(str, ",", TRUE)[[1]] # <<< here was the list
    outputVector = c()
    for(s in inputVector)
    {
        s = gsub("^\s+|\s+$", "", s)
        if(nchar(s) > 0)
            outputVector = c(outputVector, s)
    }
    return(outputVector)
}

相关内容

最新更新