R, sink/cat: Output something else than numbers?

限于喜欢 提交于 2019-12-11 06:53:41

问题


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

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

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

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

回答1:


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.

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]))


来源:https://stackoverflow.com/questions/24634499/r-sink-cat-output-something-else-than-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!