【问题标题】:Concatenate columns and add them to beginning of Data Frame连接列并将它们添加到数据框的开头
【发布时间】:2014-02-10 16:22:07
【问题描述】:

R 的菜鸟在这里。试图弄清楚一些事情。我需要构建一个将新列添加到数据集开头的函数。这个新列是用户指定的其他列中的值的串联。

假设这是名为 myDataSet 的数据集:

col_1    col_2    col_3    col_4
bat      red      1        a
cow      orange   2        b
dog      green    3        c

用户可以这样使用函数:

addPrimaryKey(myDataSet, cols=c(1,3,4))

要获得一个新数据集的结果,其中第 1、3 和 4 列连接成一个名为 ID 的列并添加到开头,如下所示:

ID        col_1    col_2    col_3    col_4
bat1a     bat      red      1        a
cow2b     cow      orange   2        b
dog4c     dog      green    3        c

这是我一直在写的剧本,但我已经盯着它看了这么久,我想我犯了一些错误。我不知道如何正确地将参数中的列号获取到粘贴函数中。

addPrimaryKey <- function(df, cols=NULL){

  newVector = rep(NA, length(cols)) ##initialize vector to length of columns

  colsN <- as.numeric(cols)

  df <- cbind(ID=paste(
    for(i in 1:length(colsN)){
      holder <- df[colsN[i]]
      holder
    }
  , sep=""), df) ##concatenate the selected columns and add as ID column to df
df
}

任何帮助将不胜感激。非常感谢

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    paste0 工作正常,在do.call 的帮助下:

    do.call(paste0, mydf[c(1, 3, 4)])
    # [1] "bat1a" "cow2b" "dog3c"
    

    因此,您的函数可能类似于:

    addPrimaryKey <- function(inDF, cols) {
      cbind(ID = do.call(paste0, inDF[cols]),
            inDF)
    }
    

    你可能还想看看interaction

    interaction(mydf[c(1, 3, 4)], drop=TRUE)
    # [1] bat.1.a cow.2.b dog.3.c
    # Levels: bat.1.a cow.2.b dog.3.c
    

    【讨论】:

    • 这很好用,非常感谢。我正在互联网上查看 do.call,但仍然无法理解它是如何与粘贴一起工作的。你能解释一下为什么会这样吗?
    • @CrayonConstantinople, mydf[c(1, 3, 4)] 实际上是一个包含三个向量的列表,因为数据帧基本上是列表。 do.call(paste0...) 等价于paste0(mydf[, 1], mydf[, 3], mydf[, 4]),其中列表中的每个值都成为paste0 的参数。
    【解决方案2】:

    这应该可以解决问题

    addPrimaryKey <-function(df, cols){
    
       q<-apply(df[,cols], 1, function(x) paste(x, collapse=""))
    
       df<-cbind(q, df)
    
       return(df)
    
    }
    

    只需为您的空值添加一些条件逻辑

    【讨论】:

      【解决方案3】:

      组合列的另外两个选项是dplyr::mutate()tidyr::unite()

      library(dplyr)
      
      df %>%
        mutate(new_col = paste0(col1, col3, col4)) %>% 
        select(new_col, everything()) # to order the column names with the new column first
      
      
      library(tidyr)
      
      df %>% 
        unite(new_col, c(col1, col3, col4), sep = '', remove = FALSE)
      

      tidy::unite() 中的默认参数是remove = TRUE,它会从数据框中删除原始列,只留下新列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-13
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        • 1970-01-01
        • 2023-03-22
        • 2021-09-27
        • 2017-09-02
        相关资源
        最近更新 更多