我需要一个包含所有对象名称的列表或矢量,并删除最后一个字符。 例如:
# if i have two objects (ob1 and other1)
ls()
##"ob1" "other1"
# I want "ob" "other"
我试图在循环中使用 substr()
和 ls()
,但我得到一个空字符向量 ("")。现在忽略循环,我必须做什么才能使 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"
关于r - 在 substr() 函数中使用 ls() 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654215/