R,接收器/目录:输出除数字以外的其他内容? [英] R, sink/cat: Output something else than numbers?

查看:82
本文介绍了R,接收器/目录:输出除数字以外的其他内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R相当陌生,我猜我的代码中有很多不充分的实践(例如,使用for循环)。我认为在此示例中,可以通过应用族中的某些方法更好地解决它,但是我不知道如何解决我的原始问题-因此,如果可能的话,请让for循环成为for循环。如果还有其他不好的事情,我很高兴听到您的意见。

I'm rather new to R and I guess there's more than one thing inadequate practice in my code (like, using a for loop). I think in this example, it could be solved better with something from the apply-family, but I would have no idea how to do it in my original problem - so, if possible, please let the for-loop be a for-loop. If something else is bad, I'm happy to hear your opinion.

但是我真正的问题是这个。我有:

But my real problem is this. I have:

name <- c("a", "a", "a", "a", "a", "a","a", "a", "a", "b", "b", "b","b", "b", "b","b", "b", "b") 
class <- c("c1", "c1", "c1", "c2", "c2", "c2", "c3", "c3", "c3","c1", "c1", "c1", "c2", "c2", "c2", "c3", "c3", "c3")
value <- c(100, 33, 80, 90, 80, 100, 100, 90, 80, 90, 80, 100, 100, 90, 80, 99, 80, 100)
df <- data.frame(name, class, value)
df

我想将其打印出来。稍后,我将使用接收器以及写入器(将其输出为html)。我都遇到了问题,所以我希望这是由同一原因引起的,如果我们解决此问题就足够了。那是代码:

And i want to print it out. I use sink as well as hwriter (to output it as a html) later on. I get the problem with both, so I hope it's caused by the same and it's enough if we solve it for sink. That's the code:

sink("stuff.txt")

for (i in 1:nrow(df)) {
    cat(" Name:")
    cat(df$name[i-1])
    cat("\n")
    cat(" Class:")
    cat(df$class[i-1])
    cat("\n")
}

sink()
file.show("stuff.txt")

我得到的部分输出类似于:

Part of the output I get is something like:

 Name:1
 Class:1
 Name:1
 Class:2
 Name:1
 Class:2

另一方面,输出I想要的应该像这样:

On the other hand, the output I want should be like:

 Name:a
 Class:c1
 Name:a
 Class:c2
 Name:a
 Class:c2


推荐答案

cat 打印数字的原因是,将字符变量放入data.frame时,您的字符变量被转换为因数。这是data.frames的默认行为。通常,这是一种更有效的存储值的方式,因为它将每个字符串值转换为唯一的整数值。这就是为什么在计算价值时会看到数字。

The reason cat was printing numbers was that your character variables were converted to "factors" when you put them in the data.frame. This is the default behavior for data.frames. It is often a more efficient way to store the values because it converts each string value to a unique integer value. That's why you see numbers when you cat the value.

如果您不想在data.frame中使用因子,则可以使用

If you don't want to use factors in your data.frame, you can use

df <- data.frame(name, class, value, stringsAsFactors=F)

,这会将值保留为字符。另外,您也可以在打印时转换为字符

and this will keep the values as characters. Alternatively, you can convert to character when you print

cat(as.character(df$name[i-1]))

这篇关于R,接收器/目录:输出除数字以外的其他内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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