【问题标题】:Removing the white space at the start of each variable IN A LIST [duplicate]删除列表中每个变量开头的空格 [重复]
【发布时间】:2021-03-07 05:03:36
【问题描述】:

我正在尝试删除每个变量开头的空格,而不是之后的空格。

我有一个这样的列表:

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))

我正在尝试得到这样的东西

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))

我尝试过的一切似乎都比应有的复杂,并且需要很长时间才能运行。

注意:trimws 不适用于列表 - 仅适用于向量 - 我希望必须更改我的输入。

谁能提出一个优雅的解决方案?

【问题讨论】:

  • sapply(input, trimws) 怎么样?
  • @Humpelstielzchen 这正是我的意思。我一定很累,我的大脑不工作了。如果您想“回答”这个问题,我将其标记为正确。谢谢。

标签: r


【解决方案1】:

你可以这样做:

sapply(input, trimws)

但请注意,结果是一个矩阵,并且 trimws 会将所有内容转换为字符。

【讨论】:

    【解决方案2】:

    这行得通吗:

    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
    

    【讨论】:

      【解决方案3】:

      你可以使用purrr::mapstringr::str_trim,像这样:

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

      编辑 如果您想忽略非字符元素并保留它们的类型,请使用map_if

      map_if(input, is.character, ~ str_trim(.x, side = "left")) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-09
        • 2017-06-11
        • 2023-03-19
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        相关资源
        最近更新 更多