【问题标题】:R - How to execute PowerShell cmds with system() or system2()R - 如何使用 system() 或 system 2() 执行 PowerShell 命令
【发布时间】:2018-10-19 01:54:32
【问题描述】:

我在 R(在 Windows 操作系统上)中工作,试图在不将文件加载到内存的情况下计算文本文件中的字数。我们的想法是获取有关文件大小、行数、字数等的一些统计信息。调用使用find 行数的 R 的 system() 函数并不难: How do I do a "word count" command in Windows Command Prompt

lineCount <- system(paste0('find /c /v "" ', path), intern = T)

我尝试使用的用于字数统计的命令是 PowerShell 命令:Measure-Object。我可以在不引发错误的情况下运行以下代码,但它返回的计数不正确。

print(system2("Measure-Object", args = c('count_words.txt', '-Word')))
[1] 127

文件count_words.txt 有数百万字。我还在一个字数少得多的 .txt 文件上对其进行了测试。

"There are seven words in this file."

但计数再次返回为 127。

print(system2("Measure-Object", args = c('seven_words.txt', '-Word')))
[1] 127

system2() 能识别 PowerShell 命令吗?使用Measure-Object 时调用函数的正确语法是什么?为什么不管实际字数多少都返回相同的值?

【问题讨论】:

    标签: r powershell cmd operating-system


    【解决方案1】:

    问题 -- 概述

    所以,这里有两个问题:

    1. 你没有告诉 system2() 使用 powershell
    2. 您没有使用正确的 powershell 语法

    解决办法

    command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
    system2("powershell", args = command)
    

    您将C:/Users/User/Documents/test2.txt 替换为文件的路径。我创建了两个 .txt 文件,其中一个带有文本“此文件中有七个单词”。另一个带有文本“但是这个文件中有八个单词”。然后我在 R 中运行了以下内容:

    command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
    system2("powershell", args = command)
    
    Lines                             Words Characters          Property           
    -----                             ----- ----------          --------           
                                          7                                        
    
    
    command <- "Get-Content C:/Users/User/Documents/test2.txt | Measure-Object -Word"
    system2("powershell", args = command)
    
    Lines                             Words Characters          Property           
    -----                             ----- ----------          --------           
                                          8                                        
    

    更多解释

    来自help("system2")

    system2调用command指定的操作系统命令。

    一个主要问题是Measure-Object 不是系统命令——它是 PowerShell 命令。 PowerShell 的系统命令是powershell,这是您需要调用的。

    此外,您还没有完全掌握正确的 PowerShell 语法。如果你看一下the docs,你会看到你真正想要的 PowerShell 命令是

    Get-Content C:/Users/User/Documents/count_words.txt | Measure-Object -Word
    

    (查看链接文档中的示例三)。

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多