Sasa88
Sasa88

Reputation: 327

in R, group dataframes rows and save into file .txt

i am new in R, i just have some basics idea in developing using R language. having a dataframe 'df', i need to group rows of dataframe, but its not work using aggregate or by, because i don't have a predefined function.

For example, if the original dataframe 'df' is something like:

id size name
1  100  5
2  100  6
3  100  72
4  200  16
5  50   12

I would like to have as output :

id size name
1  100  5 , 6 , 72
2  200  16
3  50   12

and if it's possible, to save output in file.txt? i tested with sink() and cat() but cat() don't work with dataframes and lists.

Upvotes: 0

Views: 542

Answers (2)

Sam Firke
Sam Firke

Reputation: 23014

Using the dplyr package:

results <- df %>% group_by(size) %>% summarise (rnames = paste(name,collapse = ","))

Upvotes: 0

Manohar Swamynathan
Manohar Swamynathan

Reputation: 2095

Here is few quick ways to achieve concatenating values of data frame.

R Code:

# Alternatively toString (@ David Aernburg) you can use c(character) and paste
df_a <- aggregate(name ~ size, c, data =df)
df_a <- aggregate(name ~ size, paste, data = df)


# You can also specify desired separator in collapse
df_a <- aggregate(name ~ size, paste,collapse=",",data=df)

# Using ddply you can specify desired the separator in collapse
library(dplyr)
df_a <- ddply(df, .(size), summarize, rnames = paste(name, collapse = ","))

# Write result to text file
write.table(df_a,file="df_a.txt")

Hope this helps.

Upvotes: 1

Related Questions