【问题标题】:Split string in RR中的拆分字符串
【发布时间】:2014-07-31 20:14:15
【问题描述】:

我正在尝试从 Linux 拆分“ls -lrt”命令的输出。但它只占用一个空格作为分隔符。如果有两个空格,那么它将第二个空格作为值。所以我认为我需要将多个空间压制为一个。有人对此有任何想法吗?

> a <- try(system("ls -lrt | grep -i .rds", intern = TRUE))
> a
[1] "-rw-r--r-- 1 u7x9573 sashare  2297 Jun  9 16:10 abcde.RDS"
[2] "-rw-r--r-- 1 u7x9573 sashare 86704 Jun  9 16:10 InputSource2.rds"
> str(a)
chr [1:6] "-rw-r--r-- 1 u7x9573 sashare  2297 Jun  9 16:10 abcde.RDS" ...
>
>c = strsplit(a," ")
>c
[[1]]
 [1] "-rw-r--r--" "1"          "u7x9573"    "sashare"    ""
 [6] "2297"       "Jun"        ""           "9"          "16:10"
 [11] "abcde.RDS"

[[2]]
 [1] "-rw-r--r--"       "1"                "u7x9573"          "sashare"
 [5] "86704"            "Jun"              ""                 "9"
 [9] "16:10"            "InputSource2.rds"

在下一步中,我只需要文件名,我使用了以下代码,效果很好:

mtrl_name <- try(system("ls | grep -i .rds", intern = TRUE))

【问题讨论】:

  • 您要寻找的确切结果是什么?

标签: r dataframe shiny strsplit


【解决方案1】:

这会在指定文件的数据框中返回该信息:

file.info(list.files(pattern = "[.]rds$", ignore.case = TRUE))

或者如果我们知道扩展名是小写的:

file.info(Sys.glob("*.rds"))

【讨论】:

  • 唯一的问题是接收文件名,否则没问题。对于我使用的文件名 > mtrl_name
  • 生成的数据框的行名包含文件名。 fi &lt;- file.info(Sys.glob("*.rds")); rownames(fi)
【解决方案2】:

strsplit 采用正则表达式,因此我们可以使用它们来帮助解决问题。更多信息请阅读?regex

> x <- "Spaces   everywhere right?  "
> # Not what we want
> strsplit(x, " ")
[[1]]
[1] "Spaces"     ""           ""           "everywhere" "right?"    
[6] ""          

> # Use " +" to tell it to split on 1 or more space
> strsplit(x, " +")
[[1]]
[1] "Spaces"     "everywhere" "right?"  
> # If we want to be more explicit and catch the possibility of tabs, new lines, ...
> strsplit(x, "[[:space:]]+")
[[1]]
[1] "Spaces"     "everywhere" "right?"  

【讨论】:

  • ...和 ​​strsplit(x, "\\s+") 作为另一种选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2015-08-30
  • 1970-01-01
相关资源
最近更新 更多