pill45 pill45 - 3 months ago 7
R Question

In R, output the variable of a column into a single row in a file?

This is the dataframe

df1 <- data.frame("Identifier" = sample(100001:100010, 6, replace = F),
y = sample(rnorm(10), 6, replace = T),
z = sample(rnorm(10), 6, replace = T))


When i want to output some of the information, save it into a single file, i use

write(c(nrow(df1), 2, 1), file="GSE49995_cls.txt", sep = "\t")
write(df1$y, file="GSE49995_cls.txt", append = T, sep = "\t")
write(c("df1$y","df1$x"), file="GSE49995_cls.txt", append = T, sep = "\t")


when I open the file, GSE49995_cls.txt,

6 2 1
1.226647 -0.3621273 0.5439381 -1.16689 -0.3621273
-0.3621273
df1$y
df1$x


But I want my output in this way

6 2 1
1.226647 -0.3621273 0.5439381 -1.16689 -0.3621273 -0.3621273
df1$y df1$x


Every word is separated by tab space. Anyone has idea?

Answer

You will need to change the ncolumns argument of write(), which is by default set to

ncolumns = if (is.character(x)) 1 else 5

So your first two calls are going to 5, and hence the second wraps to a second line. And your third call goes to 1 because it's a character, and hence wraps to a second line. Changing the first to length(df1$y) and the second to 2 will solve the problem.

f <- "GSE49995_cls.txt"
write(c(nrow(df1), 2, 1), file = f, sep = "\t")
write(df1$y, file = f, ncolumns = length(df1$y), append = TRUE, sep = "\t")
write(c("df1$y","df1$x"), file = f, ncolumns = 2, append = TRUE, sep = "\t")

After running this code, I get a file GSE49995_cls.txt that looks like the following.

6   2   1
0.7413901   0.9874447   -0.2382336  -0.9549439  0.9874447   -0.5963106
df1$y   df1$x

Alternatively, you could use cat() and not have to worry about this at all.

cat(c(nrow(df1), 2, 1), "\n", sep = "\t", file = f)
cat(df1$y, "\n", sep = "\t", file = f, append = TRUE)
cat(c("df1$x", "df1$y"), "\n", sep = "\t", file = f, append = TRUE)
Comments