lala
lala

Reputation: 35

How to create multiple text files for each column in a dataframe and keep the first column?

I am a new R user.

I have an excel file containing 503 columns. The first column indicates the groups while the second until the last column are numerical traits.

 Groups     length    width   ellip ... nth_trait
 AAA         2          1       7           1
 BBB         4          5       6           0
 CCC         1          6       3           5

I want to create text files in one run for each of the traits with the file name based on the trait. The code looks like this:

 raw <- read_excel("raw_data.xlsx", sheet = 1)
 raw_df <- as.data.frame(raw)

 for (i in names(raw_df)) {
 raw_file <- paste(i, ".txt", sep = "")
 write.table(raw_df[[i]], raw_file, sep = "\t", quote = F, row.names = F, col.names = T, append = F)
}

The output consists of 503 text files. Each file contains only one column which corresponds to each column in the dataframe.

But my desired output for each text file must consist of the first column (group name) and then the trait, like the ones below:

 length.txt

 Groups     length
 AAA          2
 BBB          4
 CCC          1

 width.txt

 Groups     width
 AAA          1
 BBB          5
 CCC          6

How should I modify the code? Kindly help.

Upvotes: 0

Views: 369

Answers (1)

Oliver Frost
Oliver Frost

Reputation: 827

In your write.table function, try using cbind to join the first column with whatever column is referenced in the loop:

write.table(cbind(raw_df[1], raw_df[i]), raw_file, sep = "\t", quote = F, row.names = F, col.names = T, append = F)

That should work, based on this example:

lapply(1:5, function(x){cbind(iris[1],iris[i])})

Upvotes: 1

Related Questions