Reputation: 2143
I have a matrix of character data
charMatrix <- structure(c("Bolt", "Nut Plate", "Magnet", "", "Clevis", "welded",
"", "Receptacle"), .Dim = c(4L, 2L))
[,1] [,2]
[1,] "Bolt" "Clevis"
[2,] "Nut Plate" "welded"
[3,] "Magnet" ""
[4,] "" "Receptacle"
I want to paste
the rows together and trim
them to get the vector.
[1] "Bolt Clevis" "Nut Plate welded" "Magnet" "Receptacle"
I solved it this way, but I think there must be something much simpler, either in Base R or Tidyverse.
vec <- charMatrix %>% t() %>%
as_tibble(.name_repair = "universal") %>%
summarise_all(~ str_trim(paste(., collapse = " "))) %>%
unlist() %>%
as.character()
vec
[1] "Bolt Clevis" "Nut Plate welded" "Magnet" "Receptacle"
Can you show me a more direct way to get this answer?
Upvotes: 2
Views: 55
Reputation: 181
You can do it easily with tidyverse:
library(tidyverse)
charMatrix %>%
as_tibble() %>%
unite("Var", sep = " ") %>%
mutate(Var = str_trim(Var)) %>%
pull()
Upvotes: 0
Reputation: 887391
We can use base R
by converting the matrix
to data.frame
and use paste
with do.call
trimws(do.call(paste, as.data.frame(charMatrix)))
#[1] "Bolt Clevis" "Nut Plate welded" "Magnet" "Receptacle"
The do.call
is vectorized and would be fast compared to looping.
Or using simple subsetting and paste
trimws(paste(charMatrix[,1], charMatrix[,2]))
Both are vectorized. The OP's question is to apply the function directly. Both of the solutions does that.
Upvotes: 2
Reputation: 389065
Since you have a matrix you can use rowwise apply
and trimws
to remove leading/trailing whitespaces
trimws(apply(charMatrix, 1, paste, collapse = ' '))
#[1] "BoltClevis" "Nut Platewelded" "Magnet" "Receptacle"
Or remove empty values and paste.
apply(charMatrix, 1, function(x) paste(x[x!=''], collapse = ' '))
Upvotes: 1