R output to txt file

╄→гoц情女王★ 提交于 2019-12-08 12:18:44

问题


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?


回答1:


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)



回答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.




回答3:


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


来源:https://stackoverflow.com/questions/22754432/r-output-to-txt-file

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