我有以下CSV:
color,val2,val3
blue,1,4
green,7,3
blue,4,2
red,9,3
red,2,6
blue,1,7
Run Code Online (Sandbox Code Playgroud)
我只想按颜色聚合.
当我在尝试时:
csv <- read.csv("/home/user/file.csv", stringsAsFactors=FALSE)
data <-aggregate(csv, list(csv[["color"]]), sum)
Run Code Online (Sandbox Code Playgroud)
我明白了
FUN中的错误(X [[i]],...):参数的"类型"(字符)无效
该错误来自sum(),因为您试图对color列中的字符元素求和.
sum("a")
# Error in sum("a") : invalid 'type' (character) of argument
Run Code Online (Sandbox Code Playgroud)
您需要color从x参数中删除该列,因为它未在聚合中使用,但实际上是by参数.
aggregate(csv[-1], csv["color"], sum)
# color val2 val3
# 1 blue 6 13
# 2 green 7 3
# 3 red 11 9
Run Code Online (Sandbox Code Playgroud)
但公式方法也会起作用并且更清洁(但速度更慢).
aggregate(. ~ color, csv, sum)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您需要将颜色移至另一侧,因为您确实无法聚合字符向量。您还可以按如下方式使用dplyr包:
library(dplyr)
csv %>% group_by(color) %>% summarise_each(funs(sum))
Run Code Online (Sandbox Code Playgroud)
具有以下输出:
color val2 val3
(chr) (int) (int)
1 blue 6 13
2 green 7 3
3 red 11 9
Run Code Online (Sandbox Code Playgroud)