0

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?

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.