【问题标题】:Appending arrays together in R在R中将数组附加在一起
【发布时间】:2021-10-15 03:39:51
【问题描述】:

我在将 iris3 数据集(由 Species 拆分为多维数组的经典 iris 数据集)放入 R 中新的 150x5 数据框时遇到了一些问题。我有下面的代码可以工作,但我不确定这是否使用最有效的方式,或者如果我的语法是“最佳实践”。具体来说,我想跳过分配特定于物种的数据帧的步骤,并简单地将它们全部以较短的步骤放入最终输出中。任何意见将不胜感激!

iris3 <- iris3 # load data
vec <- c('setosa', 'versicolor', 'virginica') 
ind <- seq(3)
dat <- data.frame() # initialize 

for (i in vec) {
  for (j in ind) {
    df <- as.data.frame(cbind(iris3[,,j], rep(i, 50))) # creating a column to assign Species name
    assign(x = i, value = df, envir = .GlobalEnv) # is it possible to not assign these and still get same answer? 
  }
    dat <- rbind(dat, get(i)) # when I move this up a line, it doesn't work properly
}

【问题讨论】:

    标签: r loops append rbind


    【解决方案1】:

    这会为您提供类似的输出。它同时使用purrrdplyr 包。我不确定它是否被认为是“最佳实践”,但它更简洁,更容易遵循。

    # iterate over the 3rd dimension of the array
    # convert whatever is found on the 3rd dimension as a dataframe
    # ouput is a named list
    a <- apply(iris3, 3, as.data.frame)
    
    # iterate over the named list and run a function 
    # first parameter is the data in the list and the second parameter is the name
    # adding the nm [name] as a data point in the data frame
    # output is a list
    b <- purrr::imap(a, function(dta, nm){dta$species <- nm; dta})
    
    #bind the rows together in a single dataframe
    c <- dplyr::bind_rows(b)
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2013-05-07
      相关资源
      最近更新 更多