[R] Re: Multiple vector elements into one character element

Lietz, Haiko Haiko.Lietz at gesis.org
Wed Sep 25 20:03:37 CEST 2013


Hi A.K.,

This is exactly what I needed:

x <- data.frame(Month = airquality$Month, Day = as.character(airquality$Day))
y <- aggregate(x$Day ~ x$Month, data = x, paste, collapse = ", ")
write.table(y, "y.txt", row.names = FALSE, quote = FALSE, sep = '\t')

The trick is to use collapse in the aggregate function.

Many thanks

Haiko

P.S.: Bert, dput writes R code so that's not what I needed. But many thanks also!


________________________________________
Von: r-help-bounces at r-project.org [r-help-bounces at r-project.org]" im Auftrag von "arun [smartpink111 at yahoo.com]
Gesendet: Mittwoch, 25. September 2013 16:57
An: R help
Betreff: Re: [R] Multiple vector elements into one character element

Hi,

May be this helps:
y<- aggregate(Day~Month,data=x,paste,collapse=",")
write.table(y,"file.txt",quote=FALSE)


A.K.



----- Original Message -----
From: "Lietz, Haiko" <Haiko.Lietz at gesis.org>
To: "'r-help at r-project.org'" <r-help at r-project.org>
Cc:
Sent: Wednesday, September 25, 2013 9:10 AM
Subject: [R] Multiple vector elements into one character element

Hi all,

I want to collapse multiple elements of a vector into a single comma-separated character element. I only know how to create a list of the original elements, but I have not managed to write this into a text file, which is necessary.

To illustrate, let's use the airquality dataset and extract the Month and Day columns:

library(datasets)
x <- data.frame(Month = airquality$Month, Day = as.character(airquality$Day))

Using the aggregate function

y <- aggregate(x$Day ~ x$Month, data = x, paste)

only seemingly creates what I want because the list can't be written to a file.

"1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31" for the first row should actually be a character element.

I've tried it but sapply, ascii, write.matrix don't seem get me there.

Can someone please point me towards the function I need?

Best wishes

Haiko


Haiko Lietz
GESIS - Leibniz Institute for the Social Sciences
Unter Sachsenhausen 6-8, D-50667 Köln
Tel: + 49 (0) 221 / 476 94 -223
eMail: haiko.lietz at gesis.org<mailto:haiko.lietz at gesis.org>
Web: http://www.gesis.org


    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list