R &引用;参数的长度为“0”;in-if语句

R &引用;参数的长度为“0”;in-if语句,r,R,我想根据规则计算我的数据,数字+W是数字*2 dat="1W 16 2W 16 1 16 2W 0 1W 16 16 0 4 64 64 0" data=read.table(text=dat,header=F) apply(data,c(1,2),function(y){ if(grep(pattern="W",y) ==1 ) { gsub("W",paste("*",2,

我想根据规则计算我的数据,数字+W是数字*2

dat="1W   16   2W   16
      1   16   2W    0
     1W   16   16    0
      4   64   64    0"     
data=read.table(text=dat,header=F)
apply(data,c(1,2),function(y){
     if(grep(pattern="W",y) ==1 )
     {  gsub("W",paste("*",2,sep=""),y)->s;
         eval(parse(text=s));
      } else 
        {y <- y }
      })
dat=“1W 16 2W 16
1 16 2W 0
1W 16 16 0
4   64   64    0"     
数据=读取。表格(文本=数据,标题=F)
应用(数据,c(1,2),函数(y){
如果(grep(pattern=“W”,y)==1)
{gsub(“W”,粘贴(“*”,2,sep=”“),y)->s;
eval(解析(text=s));
}否则

{y您的查询可以用以下示例说明:

grep(pattern="W","huh")
# integer(0)
没有匹配会导致长度为0的向量,因此会出现错误。请改用
grepl
,即
if(grepl(“W”,y))

grepl
具有返回值
TRUE
FALSE

作为旁注,
eval(parse(“sometext”)
被认为不是一个好主意。您可以尝试使用以下不整洁的
lappy
语句(这比
apply
更好,因为您不必先转换为矩阵):


您的查询可以通过以下示例进行说明:

grep(pattern="W","huh")
# integer(0)
没有匹配会导致长度为0的向量,因此会出现错误。请改用
grepl
,即
if(grepl(“W”,y))

grepl
具有返回值
TRUE
FALSE

作为旁注,
eval(parse(“sometext”)
被认为不是一个好主意。您可以尝试使用以下不整洁的
lappy
语句(这比
apply
更好,因为您不必先转换为矩阵):


这里有一个相当奇怪的方法,它确实很管用:

library(sfsmisc)


foo这里有一个相当奇怪的方法,它确实很管用:

library(sfsmisc)

fooR 3.4.1错误:if语句中的“参数长度为零”
如果将空向量传递到If语句中,例如:

myvariable = c()
if (myvariable){ 
    print("hello") 
} 
Error in if (myvariable) { : argument is of length zero
您将得到一个错误:

myvariable = c()
if (myvariable){ 
    print("hello") 
} 
Error in if (myvariable) { : argument is of length zero
空R向量可以通过grep等函数引发数据类型错误,例如:

if (grepl("foo", c(), fixed = TRUE)){ 
    print("yes") 
} 
哪个失败了:

Error in if (grepl("foo", c(), fixed = TRUE)) { : 
  argument is of length zero
因此,补救方法是在将变量作为参数提供给if语句或grep之类的函数之前,对变量进行更多的类型检查。

r3.4.1错误:if语句中的“参数长度为零” 如果将空向量传递到If语句中,例如:

myvariable = c()
if (myvariable){ 
    print("hello") 
} 
Error in if (myvariable) { : argument is of length zero
您将得到一个错误:

myvariable = c()
if (myvariable){ 
    print("hello") 
} 
Error in if (myvariable) { : argument is of length zero
空R向量可以通过grep等函数引发数据类型错误,例如:

if (grepl("foo", c(), fixed = TRUE)){ 
    print("yes") 
} 
哪个失败了:

Error in if (grepl("foo", c(), fixed = TRUE)) { : 
  argument is of length zero

因此,解决方法是在将变量作为参数提供给if语句或grep之类的函数之前,对变量进行更多的类型检查。

整数(0)和逻辑(0)的含义是什么?尝试
logical(1)
然后
logical(3)
看看会发生什么。它们是逻辑向量(分别用长度为1和3的默认值
FALSE
)填充。
logical(0)
表示类型为
logical
但其中没有值的向量。
integer(0)
除了整数之外是相同的。整数(0)和逻辑(0)的含义是什么?请尝试
logical(1)
,然后尝试
logical(3)
并查看发生了什么。它们是长度分别为1和3的逻辑向量(填充默认值
FALSE
)。
logical(0)
表示类型为
logical
但其中没有值的向量。
integer(0)
对于整数也是一样。正如SimonO101所指出的,你工作得太辛苦了。首先,
yAs SimonO101指出,你工作得太辛苦了。首先,
y