Add a new row in specific place in a dataframe

前端 未结 4 815
野的像风
野的像风 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:38

    If order is an important feature of your dataset then you should codify it in a safe way, e.g., by using an index variable. I wouldn't rely on rownames or the order of the data.frame rows since there are operations where they are not preserved.

    data <- read.table(text="Manufacturers       Models
    1   Audi                RS5  
    2   BMW                 M3  
    3   Cadillac            CTS-V  
    4   Lexus               ISF",header=TRUE)
    
    data$ind <- seq_len(nrow(data))
    data <- rbind(data,data.frame(Manufacturers = "Benz", Models = "C63",ind=3.1))
    data <- data[order(data$ind),]
    
    #   Manufacturers Models ind
    # 1          Audi    RS5 1.0
    # 2           BMW     M3 2.0
    # 3      Cadillac  CTS-V 3.0
    # 5          Benz    C63 3.1
    # 4         Lexus    ISF 4.0
    

提交回复
热议问题