Home > Mobile >  Present list of words in table, separate into four columns
Present list of words in table, separate into four columns

Time:04-10

I have a list of 140 words that I would like to show in a table, alphabetically. I don’t want them to show as one super long list, but rather to break into columns where appropriate (e.g. maybe four columns?) I use flextable but I’m not too sure how to do this one…

Replicate the type of data I have and the format:

install.packages("stopwords")
library(stopwords)
word<-as_tibble(head(data_stopwords_smart$en, n=140))

then i put it into a table, but it gives one very long column

wordtable<-flextable(word) %>%
 set_header_labels(rows = "") %>%
  autofit() 

CodePudding user response:

One way you could do this is split your word vector into N sections and set each as a column in a data frame. Then just set the column names to be empty except for the first. In below example I've done this manually but the process should be relatively simple to automate if you don't know in advance how long the vector will be.

word <- head(data_stopwords_smart$en, n=140)
word <- data.frame(value1=word[1:35],
                   value2=word[36:70],
                   value3=word[71:105],
                   value4=word[106:140])

wordtable <- flextable(word) %>%
  set_header_labels(value1="Value",
                    value2=NA,
                    value3=NA,
                    value4=NA) %>%
  autofit() 

Update:

Here's a function I whipped up that will automate the process. You just need to give it a vector and how many columns you want to split it into.

flextable_ncol <- function(words, ncol){
  # Split into N chunks
  word.ls <- split(words, rep(seq_along(words), each=ceiling(length(words)/ncol))[1:length(words)])
  # put NAs into chuncks to make all chuncks equal length
  if (length(word.ls[[length(word.ls)]]) < length(word.ls[[1]])){
    word.ls[[length(word.ls)]] <- c(word.ls[[length(word.ls)]], 
                                    rep(NA, length(word.ls[[1]]) - length(word.ls[[length(word.ls)]])))
  }

  # make into a data frame
  word.df <- as.data.frame(do.call(cbind, word.ls))
  # Get column names
  col.names <- c('Value', rep(NA, ncol-1))
  names(col.names) <- names(word.df)
  # make table
  wordtable <- flextable(word.df)
  wordtable <- set_header_labels(wordtable, values=col.names)
  return(wordtable)
}

You can use it like this

word <- head(data_stopwords_smart$en, n=140)
flextable_ncol(word, 8)
  • Related