在R交互式中自动响应提示

时间:2018-01-23 18:29:38

标签: r interactive non-interactive

请参阅下面我对上述问题的参考。

我在R中运行库taxize .Taxize包含一个函数,用于获取与科学名称get_tsn()相关联的稳定数字。

我可以在交互模式或非交互模式下运行它,以便我也是 是否提示在多个命中中进行选择。

交互式:

> tax.num <- get_tsn("Acer rubrum", ask=TRUE)
Retrieving data for taxon 'Acer rubrum'
tsn      target                      commonNames      nameUsage
1  28728 Acer rubrum                 red maple        accepted
2  28730 Acer rubrum ssp. drummondii NA not           accepted
3 526853 Acer rubrum var. drummondii Drummond's maple accepted
...
More than one TSN found for taxon 'Acer rubrum'!
Enter rownumber of taxon (other inputs will return 'NA'):

非交互式:

> tax.num <- get_tsn("Acer rubrum", ask=TRUE)
Retrieving data for taxon 'Acer rubrum'
Warning message:
> 1 result; no direct match found 

我需要以交互模式运行此库,以便在有多个匹配时不会得到空结果。但是,保管这个脚本对于我的数据大小来说是完全不现实的,这些数据是数以百万计的科学名称。因此,我想自动响应提示,以便答案始终为1。这可能是99%的案例的正确答案,并且最终仍会在100%的案例中找到正确的答案,其原因可能超出了本问题的范围。

因此,如何将响应自动化为1

我查看了this问题并尝试相应地修改我的代码。

options(httr_oauth_cache=T)
tax.num <- get_tsn("Acer rubrum",ask=T) 

但是,这给出了上面交互模式显示的相同结果。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

UPDATE: Ignore below. Obviously Nathan Werth posted the best answer in a comment above.

tax.num <- get_tsn_(searchterm = "Acer rubrum", rows = 1)

works wonderfully!

...

I decided to modify the source code to handle this. I suspect that there is a more desirable solution, but this one meets my needs.

Thus, in the file get_tsn.R from the source, I replaced the following block of code

      # prompt
      message("\n\n")
      print(tsn_df)
      message("\nMore than one TSN found for taxon '", x, "'!\n
      Enter rownumber of taxon (other inputs will return 'NA'):\n") 
      # prompt
      take <- scan(n = 1, quiet = TRUE, what = 'raw')

with

      take <- 1

I could have deleted other echoing to screen bits, that are unnecessary and now not true.

The revised function, which I tested using trace("get_tsn",edit=TRUE), returns as follows:

> print(tax.num)
[1] "28728"
attr(,"match")
[1] "found"
attr(,"multiple_matches")
[1] TRUE
attr(,"pattern_match")
[1] FALSE
attr(,"uri")
[1] "http://www.itis.gov/servlet/SingleRpt/SingleRpt?
search_topic=TSN&search_value=28728"
attr(,"class")
[1] "tsn"

I will recompile and install it on Linux now with the edit for use with this particular project.

I still welcome other, better answers.