Add a new row in specific place in a dataframe

前端 未结 4 830
野的像风
野的像风 2020-12-29 11:18

Heres my data:

 > data
  Manufacturers       Models
1   Audi                RS5  
2   BMW                 M3  
3   Cadillac            CTS-V  
4   Lexus           


        
4条回答
  •  我在风中等你
    2020-12-29 11:33

    I used the @Sergio Mora answer to adapt and solve the question. I saw today the question and I needed a solution.

    insert_row <- function(index, new_row, dat){
      if(is.matrix(dat) && ncol(dat) > 1){
        long <- NROW(dat)
        if(index == 1){
          new_data <- rbind(new_row, dat)  
        }
        else if(index == long){
          new_data <- rbind(dat, new_row)
        }
        else{
          new_data <- rbind(dat[1 : (index - 1), ], new_row, dat[index : long, ])
        }
        row.names(new_data) <- NULL
      }
      else if(ncol(dat) == 1 || is.vector(dat)){
        long <- length(dat)
        if(index == 1){
          new_data <- c(new_row, dat)  
        }
        else if(index == long){
          new_data <- c(dat, new_row)
        }
        else{
          new_data <- c(dat[1 : (index - 1)], new_row, dat[index : long])
        }
        row.names(new_data) <- NULL
      }
      return(new_data)
    }
    

提交回复
热议问题