Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在substr()函数中使用ls()函数时出现问题_R_Substring_Substr - Fatal编程技术网

在substr()函数中使用ls()函数时出现问题

在substr()函数中使用ls()函数时出现问题,r,substring,substr,R,Substring,Substr,我需要一个所有对象名称的列表或向量,并去掉最后一个字符。 例如: # if i have two objects (ob1 and other1) ls() ##"ob1" "other1" # I want "ob" "other" 我试图在循环中使用substr()和ls(),但得到的是一个空字符向量(“”)。现在忽略循环,我需要做什么才能在substr()中正确处理ls()[1] ob1您可以使用子函数从字符串中删除最后一个字符 > x <- c("ob1", "other

我需要一个所有对象名称的列表或向量,并去掉最后一个字符。 例如:

# if i have two objects (ob1 and other1)
ls()
##"ob1" "other1" 
# I want "ob" "other"
我试图在循环中使用
substr()
ls()
,但得到的是一个空字符向量(“”)。现在忽略循环,我需要做什么才能在
substr()中正确处理
ls()[1]


ob1您可以使用子函数从字符串中删除最后一个字符

> x <- c("ob1", "other1")
> sub(".$", "", x)
[1] "ob"    "other"
>x子(“.$”,“”,x)
[1] “ob”“其他”

您使用的是
length()
而不是
nchar()
。更改该值,您就会没事。

对于最后2个,您可以使用
sub(“{2}$”,“”,x)
同样地增加大括号内的数字,以从最后一个大括号中删除任何字符。我认为您需要在上面的代码中使用
ls()
而不是
x
> x <- c("ob1", "other1")
> sub(".$", "", x)
[1] "ob"    "other"