Combine frequency tables into a single data frame

前端 未结 3 1804
悲哀的现实
悲哀的现实 2021-02-04 19:08

I have a list in which each list item is a word frequency table derived from using \"table()\" on a different sample text. Each table is, therefore, a different length. I want

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 20:01

    Here is an inelegant way that gets the job done. I'm sure there's a 1-liner out there just for this, but I dunno where either:

        myList <- list(t1=t1, t2=t2, t3=t3)
        myList <- lapply(myList,as.data.frame,stringsAsFactors = FALSE)
        Words <- unique(unlist(lapply(myList,function(x) x[,1])))
        DFmerge <- data.frame(Words=Words)
        for (i in 1:3){
            DFmerge <- merge(DFmerge,myList[[i]],by.x="Words",by.y="Var1",all.x=TRUE)
        }
        colnames(DFmerge) <- c("Words","t1","t2","t3")
    

    And looking around a bit more, here's another way that gives output more similar to that in the linked blog post: [Edit: works now]

        myList <- list(t1=t1, t2=t2, t3=t3)
        myList <- lapply(myList,function(x) {
            A <- as.data.frame(matrix(unlist(x),nrow=1))
            colnames(A) <- names(x)
            A[,colnames(A) != ""]
            }
        )   
        do.call(rbind.fill,myList)
    

    Also ugly, so maybe a better answer will still come along.

提交回复
热议问题