add missed value based on the value of the column in r

后端 未结 3 2170
心在旅途
心在旅途 2021-01-23 01:24

This is my sample dataset:

   vector1 <-
      data.frame(
        \"name\" = \"a\",
        \"age\" = 10,
        \"fruit\" = c(\"orange\", \"cherry\", \"app         


        
3条回答
  •  无人及你
    2021-01-23 01:37

    Consider base R methods --lapply, expand.grid, transform, rbind, aggregate-- that appends all possible fruit and tag options to each dataframe and keeps the max counts.

    new_list <- lapply(list, function(df) {
      fruit_tag_df <- transform(expand.grid(fruit=c("apple", "cherry", "mango", "orange"),
                                            tag=c(1,2)),
                                name = df$name[1],
                                age = df$age[1],
                                count = 0)
    
      aggregate(.~name + age + fruit + tag, rbind(df, fruit_tag_df), FUN=max)
    })
    

    Output

    new_list
    
    # [[1]]
    #   name age  fruit tag count
    # 1    a  10  apple   1     0
    # 2    a  10 cherry   1     1
    # 3    a  10 orange   1     1
    # 4    a  10  mango   1     0
    # 5    a  10  apple   2     1
    # 6    a  10 cherry   2     0
    # 7    a  10 orange   2     0
    # 8    a  10  mango   2     0
    
    # [[2]]
    #   name age  fruit tag count
    # 1    b  33  apple   1     0
    # 2    b  33  mango   1     0
    # 3    b  33 cherry   1     0
    # 4    b  33 orange   1     0
    # 5    b  33  apple   2     1
    # 6    b  33  mango   2     1
    # 7    b  33 cherry   2     0
    # 8    b  33 orange   2     0
    
    # [[3]]
    #   name age  fruit tag count
    # 1    c  58  apple   1     1
    # 2    c  58 cherry   1     1
    # 3    c  58  mango   1     0
    # 4    c  58 orange   1     0
    # 5    c  58  apple   2     0
    # 6    c  58 cherry   2     0
    # 7    c  58  mango   2     0
    # 8    c  58 orange   2     0
    

提交回复
热议问题