Assigning group ID with ddply

后端 未结 2 1466
走了就别回头了
走了就别回头了 2021-02-01 11:01

Pretty basic performance question from an R newbie. I\'d like to assign a group ID to each row in a data frame by unique combinations of fields. Here\'s my current approach:

相关标签:
2条回答
  • 2021-02-01 11:21

    Try using the id function (also in plyr):

    df$id <- id(df[c("st.num", "st.name")], drop = TRUE)
    

    Update:

    The id function is considered deprecated since dplyr version 0.5.0. The function group_indices provides the same functionality.

    0 讨论(0)
  • 2021-02-01 11:45

    Is it necessary that the ID be a random 10 character string? If not, why not just paste together the columns of the data frame. If the IDs must be the same length in characters, convert factors to numeric, then paste them together:

    df$ID <- paste(as.numeric(df$st.num), as.numeric(df$st.name), sep = "")
    

    Then, if you really need to have 10 character IDs, I'd generate just the n number of IDs, and rename the levels of ID with them

    df$ID <- as.factor(df$ID)
    n <- nlevels(df$ID)
    
    getID <- function(n, size=10){
      out <- {}
      for(i in 1:n){
        out <- c(paste(sample(c(0:9, LETTERS, letters), size, replace=TRUE), collapse=''))
      }
      return(out)
    }
    
    newLevels <- getID(n = n)
    
    levels(df$ID) <- newLevels
    

    Also, as an aside, you don't need to use function(x) with ddply that way with transform(). This code would work just the same:

    ddply(df, c("st.num", "st.name"), transform, household=getString())
    
    0 讨论(0)
提交回复
热议问题