1

I'm trying to remove the space that at the start of each variable but not the spaces after that.

I have a list like this:

input= structure(list(X = 2:4, V1 = c(NA, NA, NA), V2 = c(" Tescho123C", 
" Tescho123A", " Tescho123B"), V3 = c(" Instrument", " Instrument", 
" Instrument"), V4 = c(" :Fanta", " :Fanta", " :Fanta"), V5 = c(" :Tool Time", 
" :Tool Time", " :Tool Time")), class = "data.frame", row.names = c(NA, 
-3L))

And I'm trying to get something like this

output = structure(list(X = 2:4, V1 = c(NA, NA, NA), V2 = c("Tescho123C", 
"Tescho123A", "Tescho123B"), V3 = c("Instrument", "Instrument", 
"Instrument"), V4 = c(":Fanta", ":Fanta", ":Fanta"), V5 = c(":Tool Time", 
":Tool Time", ":Tool Time")), class = "data.frame", row.names = c(NA, 
-3L))

Everything I've tried seems to be more complex than it should be and takes a long time to run.

NB: trimws does not work on list - only vectors - and I'd prefer for to have to change my input.

Can anyone suggest an elegant solution?

nicshah
  • 345
  • 1
  • 8

3 Answers3

2

You can do:

sapply(input, trimws)

Mind however that the result is a matrix, and trimws tunrs everything to character.

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
1

Does this work:

library(dplyr)
library(stringr)
input %>% mutate(across(starts_with('V'), ~ str_remove(., '^\\s')))
  X   V1         V2         V3     V4         V5
1 2 <NA> Tescho123C Instrument :Fanta :Tool Time
2 3 <NA> Tescho123A Instrument :Fanta :Tool Time
3 4 <NA> Tescho123B Instrument :Fanta :Tool Time
Karthik S
  • 11,348
  • 2
  • 11
  • 25
1

You can use purrr::map and stringr::str_trim, like this:

map(input, ~str_trim(., side = "left"))

EDIT If you want to ignore non-character elements, and so preserve their type, use map_if:

map_if(input, is.character, ~ str_trim(.x, side = "left")) 
jayb
  • 555
  • 3
  • 15