如何将 cat 的输出分配给一个对象? [英] How to assign output of cat to an object?

查看:30
本文介绍了如何将 cat 的输出分配给一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would it be possible in the example below to skip the step of writing to file "test.txt", i.e. assign the cat-result to an object, and still achieve the same end result?

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

I thought I'd include the full example to give background to my problem.

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

推荐答案

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

Instead of cating to a file, why not use the paste command to generate a string instead?

> 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 中,而不是执行 catreadlines.

Now instead of doing a cat then readlines you can just pass this string directly into strsplit.

这篇关于如何将 cat 的输出分配给一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆