Create a Data Frame of Unequal Lengths

后端 未结 5 1194
再見小時候
再見小時候 2020-11-29 03:23

While data frame columns must have the same number rows, is there any way to create a data frame of unequal lengths. I\'m not interested in saving them as separate elements

5条回答
  •  野性不改
    2020-11-29 04:17

    Similar problem:

     coin <- c("Head", "Tail")
    toss <- sample(coin, 50, replace=TRUE)
    
    categorize <- function(x,len){
      count_heads <- 0
      count_tails <- 0
      tails <- as.character()
      heads <- as.character()
      for(i in 1:len){
        if(x[i] == "Head"){
          heads <- c(heads,x[i])
          count_heads <- count_heads + 1
        }else {
          tails <- c(tails,x[i])
          count_tails <- count_tails + 1
        }
      }
      if(count_heads > count_tails){
        head <- heads
        tail <- c(tails, rep(NA, (count_heads-count_tails)))
      } else {
        head <- c(heads, rep(NA,(count_tails-count_heads)))
        tail <- tails
      }
      data.frame(cbind("Heads"=head, "Tails"=tail))
    }
    

    categorize(toss,50)

    Output: After the toss of the coin there will be 31 Head and 19 Tail. Then the rest of the tail will be filled with NA in order to make a data frame.

提交回复
热议问题