【问题标题】:Creating new objects by combining a vector of character strings and a numeric vector通过组合字符串向量和数值向量来创建新对象
【发布时间】:2014-04-20 02:17:55
【问题描述】:

我想在函数中创建一系列用于存储分析的新对象。我希望函数有两个参数,一个参数是一堆字符串,一个是数字向量。我对 R 相当缺乏经验,所以如果你能简单地解释一下,那将不胜感激,也有尽可能多的细节,我看到很多人在类似的情况下推荐 paste 和 assign 的组合,但我无法理解工作正常,我也看到了很多关于使用 lapply 的建议,但我无法理解 lapply 的工作原理,所以如果有人有能力用外行的方式引导我完成它,那将是一个巨大的帮助,非常感谢.

例如,

plant_species<-c("speciesA", "speciesB", "speciesC")
years<-(2005:2007)

我想从中创建以下对象:speciesA2005、speciesA2006、speciesA2007、speciesB2006、speciesB2007、speciesB2008、speciesC2006、speciesC2007、speciesC2008。

但理想情况下,我希望将植物种类和年份作为功能的一部分,例如

myfunction

}

然后我可以把它给别人,所以他们所要做的就是输入

myfunction(2005:2007, "speciesA", "speciesB", "speciesC")

但如果他们可以输入任意数量的物种,并且该函数能够识别他们输入的物种数量和年份并返回适当数量的对象,那就太好了

非常感谢

【问题讨论】:

  • 你肯定想要 2008 年? (即 B & C 序列从输入序列的开始年份多一年开始,并且比输入序列中提供的最后一年多结束?)

标签: r object


【解决方案1】:

如果我对所需输出的错字假设成立,我可以修改此设置(即,如果您真的想要所有物种的 2005-2007 而不是第一个物种的 2005-2007 和任何剩余物种的 2006-2008) :

myfunction <- function(years, species) {
  dat <- expand.grid(species, years)[,1:2]
  return(sort(sprintf("%s%s", dat$Var1, dat$Var2)))
}

myfunction(years, plant_species)
## [1] "speciesA2005" "speciesA2006" "speciesA2007" "speciesB2005" "speciesB2006" "speciesB2007"
## [7] "speciesC2005" "speciesC2006" "speciesC2007"

【讨论】:

    【解决方案2】:

    这是一个与您描述的完全一样的函数,以及“物种”本身就是一个向量的情况:

    myfunction <- function(year, ...) {
      species <- list(...)
      if (length(species[[1]]) > 1) species <- rep(species[[1]], each = length(year))
      else species <- rep(unlist(list(...)), each = length(year))
      paste0(species, year)
    }
    
    myfunction(year=2005:2007, "A", "B", "C")
    # [1] "A2005" "A2006" "A2007" "B2005" "B2006" "B2007" "C2005" "C2006" "C2007"
    
    myfunction(2005:2007, c("A", "B", "C"))
    # [1] "A2005" "A2006" "A2007" "B2005" "B2006" "B2007" "C2005" "C2006" "C2007"
    

    【讨论】:

      【解决方案3】:

      有很多方法可以解决这个问题,很多包都有功能来解决这个问题。 但是,这是一个非常基本的简单方法:

      # Step1: define an new empty vector
      newVector <- NULL
      
      # Step2:
      # start a loop over one of the variables
      # paste with all elements of second variables, and append newVector
      for(spec in plant_species)   newVector <- c(b,paste(spec,years,sep=""))  
      
      # see the results
      newVector  
      

      所以函数看起来像这样:

      myFunction <- function(years, plant_species) {
        newVector <- NULL
        for(spec in plant_species)   newVector <- c(b,paste(spec,years,sep=""))  
        return(newVector)
      }
      
      myFunction(years, plant_species)
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-25
        • 2011-12-28
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多