Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:通过R中跨列的分类变量,相当于Sumif和Countif_R_Group By_Countif_Sumifs - Fatal编程技术网

R:通过R中跨列的分类变量,相当于Sumif和Countif

R:通过R中跨列的分类变量,相当于Sumif和Countif,r,group-by,countif,sumifs,R,Group By,Countif,Sumifs,假设我有一个包含10列的数据集。其中9个是数字,一个是分类值,如高、中、低。我想通过R中所有9个数字列的分类变量进行总结(类似于excel中的sumif和countif) 如何做到这一点?我对R很陌生,任何帮助都会很好!谢谢 如果您的数据框被称为df,而您的分类变量被称为group.var,那么您可以执行以下操作: library(dplyr) df %>% group_by(group.var) %>% summarise_each(funs(n(),sum)) 内置ir

假设我有一个包含10列的数据集。其中9个是数字,一个是分类值,如高、中、低。我想通过R中所有9个数字列的分类变量进行总结(类似于excel中的sumif和countif)


如何做到这一点?我对R很陌生,任何帮助都会很好!谢谢

如果您的数据框被称为
df
,而您的分类变量被称为
group.var
,那么您可以执行以下操作:

library(dplyr)

df %>% group_by(group.var) %>%
   summarise_each(funs(n(),sum))
内置
iris
数据帧的示例:

iris %>% group_by(Species) %>%
  summarise_each(funs(n(), sum))

     Species Sepal.Length_n Sepal.Width_n Petal.Length_n Petal.Width_n Sepal.Length_sum Sepal.Width_sum Petal.Length_sum Petal.Width_sum
      (fctr)          (int)         (int)          (int)         (int)            (dbl)           (dbl)            (dbl)           (dbl)
1     setosa             50            50             50            50            250.3           171.4             73.1            12.3
2 versicolor             50            50             50            50            296.8           138.5            213.0            66.3
3  virginica             50            50             50            50            329.4           148.7            277.6           101.3

还有许多其他选项(例如,
data.table
包,以及使用
tapply
aggregate
等的base R解决方案)

在进入令人困惑的包数组之前,了解这些类型操作的base R习惯用法是有帮助的(尽管它们可能很有用)

将拆分data.frame并对每个子集应用函数。如果需要对向量而不是data.frame进行操作,请参见
?t请参见

tapply(iris$Sepal.Length, iris$Species, summary)

这是聚合,在R中有
聚合
,etcI在库中不断出错(dplyr):即使我成功地从Cran安装了包,也没有名为“dplyr”的包。有什么提示吗?
tapply(iris$Sepal.Length, iris$Species, summary)