在 substr() 函数中使用 ls() 函数时出现问题
Trouble using ls() function inside substr() function
我需要一个包含所有对象名称的列表或向量,并删除最后一个字符。
例如:
# if i have two objects (ob1 and other1)
ls()
##"ob1" "other1"
# I want "ob" "other"
我试图在 ls()
的循环中使用 substr()
,但我得到一个空字符向量 ("")。现在忽略循环,我需要做什么才能让 ls()[1]
在 substr()
中得到正确处理?
ob1 <– NULL
substr(ls()[1],1,length(ls()[1])-1)
##[1] ""
substr(paste(ls()[1]),1,length(ls()[1])-1)
##[1] ""
substr(toString(ls()[1]),1,length(ls()[1])-1)
##[1] ""
substr(as.character(ls()[1]),1,length(ls()[1])-1)
##[1] ""
您可以使用 sub 函数从字符串中删除最后一个字符。
> x <- c("ob1", "other1")
> sub(".$", "", x)
[1] "ob" "other"
您正在使用 length()
而不是 nchar()
。改变它,你会没事的。
我需要一个包含所有对象名称的列表或向量,并删除最后一个字符。 例如:
# if i have two objects (ob1 and other1)
ls()
##"ob1" "other1"
# I want "ob" "other"
我试图在 ls()
的循环中使用 substr()
,但我得到一个空字符向量 ("")。现在忽略循环,我需要做什么才能让 ls()[1]
在 substr()
中得到正确处理?
ob1 <– NULL
substr(ls()[1],1,length(ls()[1])-1)
##[1] ""
substr(paste(ls()[1]),1,length(ls()[1])-1)
##[1] ""
substr(toString(ls()[1]),1,length(ls()[1])-1)
##[1] ""
substr(as.character(ls()[1]),1,length(ls()[1])-1)
##[1] ""
您可以使用 sub 函数从字符串中删除最后一个字符。
> x <- c("ob1", "other1")
> sub(".$", "", x)
[1] "ob" "other"
您正在使用 length()
而不是 nchar()
。改变它,你会没事的。