R - creating rows based upon counter value

前端 未结 5 1977
一个人的身影
一个人的身影 2021-01-26 22:22
input <- read.table(header=F, text=\"abc 2 
                def 3 
                pq 2\")
colnames(input) <- c(\"text\",\"count\")

I have input

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 23:07

    Use row indexing:

    input[rep(seq(nrow(input)),input$count),]
    # or even
    input[rep(rownames(input),input$count),]
    
    #    text count
    #1    abc     2
    #1.1  abc     2
    #2    def     3
    #2.1  def     3
    #2.2  def     3
    #3     pq     2
    #3.1   pq     2
    

    The second option works because you can index by the character vector in the rownames as well as colnames, e.g.:

    rownames(input)
    #[1] "1" "2" "3"
    input["1",]
    #  text count
    #1  abc     2
    

提交回复
热议问题