Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "invalid 'type' (character) of argument" error with aggregate()

Tags:

r

aggregate

I have the following CSV:

color,val2,val3
blue,1,4
green,7,3
blue,4,2
red,9,3
red,2,6
blue,1,7

I simply want to aggregate by color.

When I'm trying:

csv <- read.csv("/home/user/file.csv", stringsAsFactors=FALSE)
data <-aggregate(csv, list(csv[["color"]]), sum)

I get

Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument

like image 258
Evgenij Reznik Avatar asked Jan 31 '16 22:01

Evgenij Reznik


2 Answers

In this case, you need to move color to the other side since you really can't aggregate on a character vector. You can also use dplyr package as follows:

library(dplyr)
csv %>% group_by(color) %>% summarise_each(funs(sum))

With following output:

  color  val2  val3
  (chr) (int) (int)
1  blue     6    13
2 green     7     3
3   red    11     9
like image 144
Gopala Avatar answered Nov 12 '22 07:11

Gopala


That error is coming from sum(), because you are attempting to sum the character elements in the color column.

sum("a")
# Error in sum("a") : invalid 'type' (character) of argument

You need to remove the color column from the x argument, since it is not being used in aggregation, but is actually the by argument.

aggregate(csv[-1], csv["color"], sum)
#   color val2 val3
# 1  blue    6   13
# 2 green    7    3
# 3   red   11    9

But the formula method would also work and is cleaner (but slower).

aggregate(. ~ color, csv, sum)
like image 42
Rich Scriven Avatar answered Nov 12 '22 06:11

Rich Scriven