gpt4 book ai didi

r - 猫和打印有什么区别?

转载 作者:行者123 更新时间:2023-12-02 02:00:30 24 4
gpt4 key购买 nike

catprint 似乎都在 R 中提供了“打印”功能。

x <- 'Hello world!\n'
cat(x)
# Hello world!
print(x)
# [1] "Hello world!\n"

我的印象是 cat 最类似于典型的“打印”功能。什么时候使用cat,什么时候使用print

最佳答案

cat 仅对原子类型(逻辑、整数、实数、复数、字符)和名称有效。这意味着您不能在非空列表或任何类型的对象上调用 cat。实际上,它只是将参数转换为字符并连接,因此您可以想到类似 as.character() %>% Paste() 的东西。

print 是一个通用函数,因此您可以为某个 S3 类定义特定的实现。

> foo <- "foo"
> print(foo)
[1] "foo"
> attributes(foo)$class <- "foo"
> print(foo)
[1] "foo"
attr(,"class")
[1] "foo"
> print.foo <- function(x) print("This is foo")
> print(foo)
[1] "This is foo"

cat 和 print 之间的另一个区别是返回值。 cat 无形地返回 NULL,而 print 返回其参数。 print 的这个属性在与管道结合使用时特别有用:

coefs <- lm(Sepal.Width ~  Petal.Length, iris) %>%
print() %>%
coefficients()

大多数时候您想要的是打印cat 对于将字符串写入文件之类的事情很有用:

sink("foobar.txt")
cat('"foo"\n')
cat('"bar"')
sink()

pointed通过 baptiste您可以使用 cat 将输出直接重定向到文件。所以上面的等价物是这样的:

cat('"foo"', '"bar"', file="foobar.txt", sep="\n")

如果你想增量地写入行,你应该使用 append 参数:

cat('"foo"', file="foobar.txt", append=TRUE)
cat('"bar"', file="foobar.txt", append=TRUE)

sink 方法相比,根据我的口味,它过于冗长,但它仍然是一种选择。

关于r - 猫和打印有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com