【问题标题】:How to assign output of cat to an object?如何将 cat 的输出分配给对象?
【发布时间】:2010-11-27 04:40:20
【问题描述】:

如何在下面的示例中跳过写入文件“test.txt”的步骤,即将 cat-result 分配给一个对象,并且仍然获得相同的最终结果?

我想我会包含完整的示例来为我的问题提供背景。

test <- c("V 1", "x", "1 2 3", "y", "3 5 8", "V 2", "x", "y", "V 3", "y", "7 2 1", "V 4", "x", "9 3 7", "y")

# Write selection to file
cat(test, "\n", file="test.txt")
test2 <- readLines("test.txt")
test3 <- strsplit(test2, "V ")[[1]][-1]

# Find results
x <- gsub("([0-9]) (?:x )?([0-9] [0-9] [0-9])?.*", "\\1 \\2 ", test3, perl = TRUE)
y <- gsub("([0-9]).* y ?([0-9] [0-9] [0-9])?.*", "\\1 \\2 ", test3, perl = TRUE)

# Eliminate tests with no results
x1 <- x[regexpr("[0-9] ([^0-9]).*", x) == -1]
y1 <- y[regexpr("[0-9] ([^0-9]).*", y) == -1]

# Dataframe of results
xdf1 <- read.table(textConnection(x1), col.names=c("id","x1","x2","x3"))
ydf1 <- read.table(textConnection(y1), col.names=c("id","y1","y2","y3"))
closeAllConnections()

# Dataframe of tests with no results
x2 <- x[regexpr("[0-9] ([^0-9]).*", x) == 1]
y2 <- y[regexpr("[0-9] ([^0-9]).*", y) == 1]

df1 <- as.integer(x2[x2 == y2])
df1 <- data.frame(id = df1)

# Merge dataframes
results <- merge(xdf1, ydf1, all = TRUE)
results <- merge(results, df1, all = TRUE)
results

结果:

  id x1 x2 x3 y1 y2 y3
1  1  1  2  3  3  5  8
2  2 NA NA NA NA NA NA
3  3 NA NA NA  7  2  1
4  4  9  3  7 NA NA NA

【问题讨论】:

    标签: r variable-assignment


    【解决方案1】:

    作为更通用的解决方案,您可以使用捕获输出功能。它会生成一个字符向量,其中的元素对应于输出的每一行。

    你的例子:

    test2<-capture.output(cat(test))
    

    这是一个多行示例:

    > out<-capture.output(summary(lm(hwy~cyl*drv,data=mpg)))
    > out
     [1] ""                                                               
     [2] "Call:"                                                          
     [3] "lm(formula = hwy ~ cyl * drv, data = mpg)"                      
     [4] ""                                                               
     [5] "Residuals:"                                                     
     [6] "    Min      1Q  Median      3Q     Max "                       
     [7] "-8.3315 -1.4139 -0.1382  1.6479 13.5861 "                       
     [8] ""                                                               
     [9] "Coefficients:"                                                  
    [10] "            Estimate Std. Error t value Pr(>|t|)    "           
    [11] "(Intercept)  32.1776     1.2410  25.930  < 2e-16 ***"           
    [12] "cyl          -2.0049     0.1859 -10.788  < 2e-16 ***"           
    [13] "drvf          8.4009     1.8965   4.430 1.47e-05 ***"           
    [14] "drvr          8.2509     6.4243   1.284    0.200    "           
    [15] "cyl:drvf     -0.5362     0.3422  -1.567    0.119    "           
    [16] "cyl:drvr     -0.5248     0.8379  -0.626    0.532    "           
    [17] "---"                                                            
    [18] "Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 "
    [19] ""                                                               
    [20] "Residual standard error: 2.995 on 228 degrees of freedom"       
    [21] "Multiple R-squared: 0.7524,\tAdjusted R-squared: 0.747 "         
    [22] "F-statistic: 138.6 on 5 and 228 DF,  p-value: < 2.2e-16 "       
    [23] ""    
    

    【讨论】:

      【解决方案2】:

      为什么不使用cat 生成文件,而不是使用paste 命令来生成字符串?

      > paste(test, collapse="\n")
      [1] "V 1\nx\n1 2 3\ny\n3 5 8\nV 2\nx\ny\nV 3\ny\n7 2 1\nV 4\nx\n9 3 7\ny"
      

      现在,您可以直接将此字符串传递给strsplit,而不是cat 然后readlines

      【讨论】:

        【解决方案3】:

        试试

        > f <- textConnection("test3", "w")
        > cat(test, "\n", file=f)
        > test3
        [1] "V 1 x 1 2 3 y 3 5 8 V 2 x y V 3 y 7 2 1 V 4 x 9 3 7 y "
        > close(f)
        

        【讨论】:

          【解决方案4】:

          还有一个 assign 语句,它允许您建立一个名称并为其设置一个对象。如果您想迭代一堆测试并用动态值命名它们,这非常有用。

          assign("mary", paste(test,sep="\n"))

          将粘贴语句分配给玛丽。但是,假设您正在运行一堆回归并希望您的回归对象由预测器命名。你可以做类似的事情

          assign(paste("myRegression",names(dataframe)[2],sep=""), lm(dataframe$response~dataframe[,2]))
          

          这会给你对象

          myRegressionPredictorName 作为线性模型。

          【讨论】:

            【解决方案5】:

            试试下面的代码:

            writeLines(capture.out((summary(lm(hwy~cyl*drv,data=mpg)),con="summary.txt",sep="\n")

            然后你可以打开txt文件“summary.txt”来查看你的结果。

            【讨论】:

              猜你喜欢
              • 2018-05-18
              • 1970-01-01
              • 2021-01-31
              • 1970-01-01
              • 2011-07-19
              • 2020-05-07
              • 2019-11-11
              • 1970-01-01
              • 2018-06-26
              相关资源
              最近更新 更多