警告意味着什么:条件的长度> 1,只使用第一个元素

问题描述 投票:0回答:1

我收到一个警告:“条件长度> 1,只使用第一个元素”,当我尝试使用以下函数fixED时:

> fixED
function(x) {
    if(nchar(x) == 5) {
        return(x)
    }
    else if(nchar(x) == 3) {
        return(gsub('^(.{2})(.*)$', '\\100\\2', x))
    } 
    else if(nchar(x) == 4) {
        return(gsub('^(.{2})(.*)$', '\\10\\2', x))
    }
}

以下是完整的警告:

Warning messages:
1: In if (nchar(x) == 5) { :
  the condition has length > 1 and only the first element will be used
2: In if (nchar(x) == 4) { :
  the condition has length > 1 and only the first element will be used
3: In if (nchar(x) == 3) { :
  the condition has length > 1 and only the first element will be used

我知道这里有一些与此类似的其他问题,但没有一个问题可以解释我的问题。听起来好像R语句if语句中的逻辑表达式返回的矢量> 1。

但是,我不明白这是怎么回事,因为我很确定它们是1的逻辑向量。的确,以下似乎证明:

> length((nchar("43") ==2))
[1] 1

任何人都可以看到这里的问题是什么?我此刻难过。我想要应用此函数的数据如下所示:

> df.short
     AD ED
9918 57 84
9919 57 84
9920 57 84
9921 57 84
9922 57 84
9923 57 84
9924 57 84
9925 57 85
9926 57 85
9927 57 85
9928 57 85

我这样申请:

df.short$test <- fixED(paste(df.short$AD, df.short$ED, sep=""))
r user-defined-functions
1个回答
1
投票

这个,

paste(df.short$AD, df.short$ED, sep="")

是一个向量,而不是长度为1,所以当你将它传递给你的函数时,你正在测试一个标量的向量:

nchar(x) == 5

我建议使用apply函数循环你的函数,比如

mapply(fixED, x = paste(df.short$AD, df.short$ED, sep=""))
© www.soinside.com 2019 - 2024. All rights reserved.