如何将 cat 的输出分配给一个对象?

编程入门 行业动态 更新时间:2024-10-25 14:28:47
本文介绍了如何将 cat 的输出分配给一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何在下面的示例中跳过写入文件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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 07:22:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   对象   cat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!