在R中按组添加上一行到相应的列

时间:2018-01-28 00:02:54

标签: r

我将发布一个可重现的例子。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NR_OF_ENTRIES 10
#define PATH_LEN    256

int main (){
    FILE *fp;
    int status;
    char path[PATH_LEN];

    int i,j = 0;

    size_t nr_of_elements = MAX_NR_OF_ENTRIES;

    char **old_arr;
    char **new_arr;

    char **s = calloc(nr_of_elements, sizeof(char*));

    fp = popen("/bin/ls -l", "r");

    if (fp == NULL){
        printf("fp error\n");
    }

    while(fgets(path,PATH_LEN,fp) != NULL){

        printf("%s\n", path );

        char *str = malloc(strlen(path)+1);
        strcpy(str, path);
        s[i] = str;

        i++;

        if(i>=nr_of_elements ) 
        {
            printf("resizing\n");     
            size_t old_size = nr_of_elements; 
            nr_of_elements = 4*nr_of_elements; // increase size for `s` 4 times (you can invent something else here)
            old_arr = s; 

            // allocating a bigger copy of the array s, copy it inside, and redefine the pointer:

            new_arr = calloc(nr_of_elements, sizeof(char*));

            if (!new_arr) 
             {
                 perror("new calloc failed");
                 exit(EXIT_FAILURE);
             }

            memcpy (new_arr, old_arr, sizeof(char*)*old_size);   // notice the use of `old_size` 

            free (old_arr);
            s = new_arr;
         }
    }


    status = pclose(fp);
    if (status==-1){
        printf("pclose error");
    }else{
        printf("pclose was fine!\n");
    }

    // Print and free the allocated strings
    for(j=0; j< i; j++){
        printf("%s\n", s[j] );    
        free (s[j]);        
    }

    free(s);
    return 0;
}

我想要这样的结果作为最终结果。

id <- c(1,1,1,1,2,2,1,1)
group <- c("a","b","c","d","a","b","c","d")
df <- data.frame(id, group)

仅提及身份证件的顺序。我有另一列作为时间戳。

2 个答案:

答案 0 :(得分:2)

来自dplyr的{​​{1}}和rleid的一个解决方案:

data.table

答案 1 :(得分:1)

如果我理解你的问题是正确的,你可以使用以下功能:

id <- c(1,1,1,1,2,2,1,1)
group <- c("a","b","c","d","a","b","c","d")
df <- data.frame(id, group)

add_group2 <- function(df) {
  n <-length(group)
  group2 <- as.character(df$group[2:n])
  group2 <- c(group2, "-")
  group2[which(c(df$id[-n] - c(df$id[2:n]), 0) != 0)] <- "-"
  return(data.frame(df, group2))
}
add_group2(df)

结果应该是:

 id group group2
1  1     a      b
2  1     b      c
3  1     c      d
4  1     d      -
5  2     a      b
6  2     b      -
7  1     c      d
8  1     d      -