eric_kernfeld
eric_kernfeld

Reputation: 528

R aggregate turns strings into numbers. Why does this happen and how can I avoid it?

Why does this code print only numbers to the console? How can I get a list with names 1 through 13 and contents a,n ; b,o; et cetera?

aggregate(letters, by = data.frame(rep(1:13, 2)), head, simplify = F)

I'm using R 3.5.1.

I haven't found a duplicate yet. Here is what I have found so far on similar topics.

A similar but not identical question:

R Aggregate FUN=head

An apparently similar question that is actually about aggregating numbers:

R: Aggregate character strings

Upvotes: 0

Views: 165

Answers (1)

eric_kernfeld
eric_kernfeld

Reputation: 528

letters is coerced to a dataframe. It becomes a factor. Factors are stored as integers in R. If the levels are lost somewhere, they often start to just look like integers. Try this instead:

aggregate(data.frame(letters, stringsAsFactors = F), by = data.frame(rep(1:13, 2)), head, simplify = F)

Upvotes: 1

Related Questions