【问题标题】:Trouble using ls() function inside substr() function在 substr() 函数中使用 ls() 函数时遇到问题
【发布时间】:2015-04-15 15:21:41
【问题描述】:

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

# 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] ""

【问题讨论】:

    标签: r substring substr


    【解决方案1】:

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

    > x <- c("ob1", "other1")
    > sub(".$", "", x)
    [1] "ob"    "other"
    

    【讨论】:

    • 对于最后 2 个,您可以使用 sub(".{2}$", "", x) 同样增加大括号内的数字以从最后一个中删除任何字符。而且我认为您需要在上面的代码中使用ls() 而不是x
    【解决方案2】:

    您使用的是length() 而不是nchar()。改变它,你会没事的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多