在R语言中是否有一个“引用单词”操作符?

3
在R中,是否有类似于Perl中的qw的“引用单词”运算符?qw是一个引用运算符,它允许您创建一个带有引号的项目列表,而不必逐个引用每个项目。以下是没有使用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 这样的东西。但对于那些从未使用过 Perl 的人来说,了解 qw() 究竟是做什么的会很好。 - Rich Scriven
感谢您对更好地解释qw的建议!刚刚进行了编辑。 - Christopher Bottoms
2个回答

4

尝试使用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中,即使用花括号或圆括号包裹,空格分隔的裸词也不是有效语法。你必须对它们进行引用。


1
一组引号比几十个更好! - Christopher Bottoms

1

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

Which prints

 [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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接