Jin
Jin

Reputation: 1223

R output to txt file

I have a data frame in 2 columns

userID itemID
1       101
1       103
1       107
2       102
2       103
3       104  
...

The output I want is to write a file to result.txt
1 \t 101 , 103 , 107
2 \t 102 , 103
3 \t 104
here \t means a tab distance between userID and the itemID. This is not as aligned as a table. I am more of Java and Python background, what are the lower level writing commands in R for general purpose?

Upvotes: 0

Views: 5756

Answers (3)

Thomas
Thomas

Reputation: 44527

Here's another base solution using aggregate:

> write.table(aggregate(d$itemID, list(d$userID), paste, collapse=' , '),
              file='result.txt', sep='\t', col.names=FALSE, row.names=FALSE, quote=FALSE)
1       101 , 103 , 107
2       102 , 103
3       104

Upvotes: 0

Chitrasen
Chitrasen

Reputation: 1726

you can use dplyr package for this

library(dplyr)

df.summary <- df %.%
  group_by(userId) %.%
  summarise(itemId = paste(itemId, collapse = ","))


write.table(x=df.summary,file='new_file.tsv',sep='\t',row.names=F)

Upvotes: 2

jbaums
jbaums

Reputation: 27388

A bit messy, but this will do the trick, writing the output to output.txt:

d <- read.table(text='userID itemID
1       101
1       103
1       107
2       102
2       103
3       104', header=T)

cat(sapply(split(d, d$userID), function(x) 
  paste(x$userID[1], paste(x$itemID, collapse=' , '), sep='\t')), 
  sep='\n', file='output.txt')

See ?cat and ?paste for further details.

Upvotes: 2

Related Questions