3

Let's have a following datafrane:

df <- data.frame(c("a", "c ","e "), c("b ", "d", "f "))
colnames(df) <- c("X1", "X2")
df
  X1 X2
1  a b 
2 c   d
3 e  f

How to transform the given data.frame to one character vector without spaces?

#Expected result:
#vector
#[1]"abcdef"
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Mikołaj
  • 385
  • 4
  • 17
  • 2
    Related post: https://stackoverflow.com/questions/2545228/converting-a-dataframe-to-a-vector-by-rows – zx8754 Feb 19 '19 at 15:00

5 Answers5

5

Another solution from base R.

paste(trimws(as.vector(t(df))), collapse = "")
# [1] "abcdef"
www
  • 38,575
  • 12
  • 48
  • 84
3

Transpose df, unravel it into a vector, trim the spaces and paste the components together:

paste(trimws(c(t(df))), collapse = "")
## [1] "abcdef"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • `c` is more efficient than `as.vector` in my solution. Thanks for sharing your solution – www Feb 19 '19 at 14:57
  • The documentation cautions against using `c` over `as.vector`. I agree, since it’s hard to read. `as.vector` makes the intentions clearer. – Konrad Rudolph Feb 19 '19 at 14:58
  • It claims as.vector is more intuitive. It does not warn against using it. Note that some of the recommendations in the documentation are not the best. For example, intidyverse would never have been developed in its current form had it followed recommendations in the documentation. – G. Grothendieck Feb 19 '19 at 15:24
3

An idea using gsub to remove unwanted spaces,

gsub(' ', '', paste(unlist(t(df)), collapse =  ''))
#[1] "abcdef"
Sotos
  • 51,121
  • 6
  • 32
  • 66
3

As noted in the comments, t already converts df to a matrix, so the following works:

paste(trimws(t(df)), collapse = "")
# [1] "abcdef"
acylam
  • 18,231
  • 5
  • 36
  • 45
2

One option is paste after removing the leading/lagging spaces with trimws

paste(do.call(paste0, lapply(df, trimws)), collapse="")
#[1] "abcdef"

Or using tidyverse

library(tidyverse)
df %>% 
  mutate_all(str_squish) %>% 
  pmap_chr(paste, sep="") %>%
  paste(., collapse="")
#[1] "abcdef"
akrun
  • 874,273
  • 37
  • 540
  • 662