R: Find missing columns, add to data frame if missing

前端 未结 3 1886
醉话见心
醉话见心 2020-12-16 23:37

I\'d like to write some code that would take a given data frame, check to see if any columns are missing, and if so, add the missing columns filled with 0 or NA. Here\'s wha

3条回答
  •  悲&欢浪女
    2020-12-17 00:10

    Here's a straightforward approach

    df <- data.frame(a=1:4, e=4:1)
    nms <- c("a", "b", "d", "e")   # Vector of columns you want in this data.frame
    
    Missing <- setdiff(nms, names(df))  # Find names of missing columns
    df[Missing] <- 0                    # Add them, filled with '0's
    df <- df[nms]                       # Put columns in desired order
    #   a b d e
    # 1 1 0 0 4
    # 2 2 0 0 3
    # 3 3 0 0 2
    # 4 4 0 0 1
    

提交回复
热议问题