【问题标题】:Is there a "quote words" operator in R? [duplicate]R中是否有“引用词”运算符? [复制]
【发布时间】:2015-05-01 03:42:21
【问题描述】:

R 中是否有“引号”运算符,类似于 Perl 中的qwqw 是一个引用运算符,允许您创建引用项目的列表,而无需单独引用每个项目。

如果没有qw(即使用几十个引号和逗号),您将如何做到这一点:

#!/bin/env perl
use strict;
use warnings;

my @NAM_founders = ("B97",    "CML52",  "CML69", "CML103", "CML228", "CML247",
                    "CML322", "CML333", "Hp301", "Il14H",  "Ki3",    "Ki11",
                    "M37W",   "M162W",  "Mo18W", "MS71",   "NC350",  "NC358"
                    "Oh7B",   "P39",    "Tx303", "Tzi8",
                   );

print(join(" ", @NAM_founders)); # Prints array, with elements separated by spaces

这里是做同样的事情,但qw 更简洁:

#!/bin/env perl
use strict;
use warnings;

my @NAM_founders = qw(B97    CML52  CML69  CML103 CML228 CML247 CML277
                      CML322 CML333 Hp301  Il14H  Ki3    Ki11   Ky21
                      M37W   M162W  Mo18W  MS71   NC350  NC358  Oh43
                      Oh7B   P39    Tx303  Tzi8
                   );

print(join(" ", @NAM_founders)); # Prints array, with elements separated by spaces

我已经搜索过但没有找到任何东西。

【问题讨论】:

  • 可能类似于stringi::stri_split_boundariesstri_extract_*_words。但如果知道qw() 是做什么的,对于那些从未使用过 Perl 的人来说,那就太好了
  • 感谢建议更好地解释qw!刚刚编辑。

标签: r quotes


【解决方案1】:

尝试使用scan 和文本连接:

qw=function(s){scan(textConnection(s),what="")}
NAM=qw("B97      CML52    CML69    CML103    CML228   CML247  CML277
                  CML322   CML333   Hp301    Il14H     Ki3      Ki11    Ky21
                  M37W     M162W    Mo18W    MS71      NC350    NC358   Oh43
                  Oh7B     P39      Tx303    Tzi8")

即使引号中的数据是数字,这也将始终返回一个字符串向量:

> qw("1 2 3 4")
Read 4 items
[1] "1" "2" "3" "4"

我认为你不会变得更简单,因为空格分隔的裸词在 R 中不是有效的语法,即使用大括号或括号括起来也是如此。你必须引用它们。

【讨论】:

  • 一组报价胜过几十个!
【解决方案2】:

对于 R,我能想到或目前发现的最接近的方法是创建一个文本块,然后使用 strsplit 将其分解,因此:

#!/bin/env Rscript
NAM_founders <- "B97      CML52    CML69    CML103    CML228   CML247  CML277
                 CML322   CML333   Hp301    Il14H     Ki3      Ki11    Ky21
                 M37W     M162W    Mo18W    MS71      NC350    NC358   Oh43
                 Oh7B     P39      Tx303    Tzi8"

NAM_founders <- unlist(strsplit(NAM_founders,"[ \n]+"))

print(NAM_founders)

打印出来的

 [1] "B97"    "CML52"  "CML69"  "CML103" "CML228" "CML247" "CML277" "CML322"
 [9] "CML333" "Hp301"  "Il14H"  "Ki3"    "Ki11"   "Ky21"   "M37W"   "M162W"
[17] "Mo18W"  "MS71"   "NC350"  "NC358"  "Oh43"   "Oh7B"   "P39"    "Tx303"
[25] "Tzi8"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2014-11-19
    • 2021-01-03
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多