Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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_Split_Plyr - Fatal编程技术网

R中的值之和,其中列中的值介于两个数字之间

R中的值之和,其中列中的值介于两个数字之间,r,split,plyr,R,Split,Plyr,我尝试获取data.frame并聚合一列的值,按其他列中的值排序,最后一列中的值位于特定条件之间。在SQL中,我会做一个简单的GROUPBY并编写一个循环,但我刚刚开始学习R,很难理解语法。基本上,我有一个如下所示的数据集: Type Type2 Bucket Value A 1 1 1 A 2 1 2 A 3 1 1 A 4 1 3

我尝试获取data.frame并聚合一列的值,按其他列中的值排序,最后一列中的值位于特定条件之间。在SQL中,我会做一个简单的GROUPBY并编写一个循环,但我刚刚开始学习R,很难理解语法。基本上,我有一个如下所示的数据集:

Type    Type2   Bucket  Value
   A    1       1       1
   A    2       1       2
   A    3       1       1
   A    4       1       3
   A    5       1       1
   A    1       2       1
   A    2       2       2
   A    3       2       1
   A    4       2       3
Type    Type2   Bucket  Value
A       <4      1       4
A       >=4     1       4
A       <4      2       5
A       >=4     2       3
我希望输出如下:

Type    Type2   Bucket  Value
   A    1       1       1
   A    2       1       2
   A    3       1       1
   A    4       1       3
   A    5       1       1
   A    1       2       1
   A    2       2       2
   A    3       2       1
   A    4       2       3
Type    Type2   Bucket  Value
A       <4      1       4
A       >=4     1       4
A       <4      2       5
A       >=4     2       3
键入类型2存储桶值
A=414
A=423

在我看来,这很容易,但我来自SQL背景,并试图在R中实现。我已经将一些函数(如split和ddply)弄乱了,并取得了一些成功,但不能完全将它们组合在一起。谢谢。

您可以使用
dplyr
完成此操作。假设您有多个
类型

library(dplyr)

df %>%
  group_by(Type, Bucket, Type2 = ifelse(Type2 < 4, "<4", ">=4")) %>%
  summarize(Value = sum(Value)) %>%
  select(Type, Type2, Bucket, Value)
结果:

# A tibble: 4 x 4
# Groups:   Type, Bucket [2]
    Type Type2 Bucket Value
  <fctr> <chr>  <int> <int>
1      A    <4      1     4
2      A   >=4      1     4
3      A    <4      2     4
4      A   >=4      2     3
  Type Type_2 Bucket Value
1    A     <4      1     4
2    A    >=4      1     4
3    A     <4      2     4
4    A    >=4      2     3
df = structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L), .Label = "A", class = "factor"), Type2 = c(1L, 2L, 3L, 
4L, 5L, 1L, 2L, 3L, 4L), Bucket = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L), Value = c(1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L, 3L)), .Names = c("Type", 
"Type2", "Bucket", "Value"), class = "data.frame", row.names = c(NA, 
-9L))

如果您的背景是SQL,您可能会觉得与
dplyr
或类似于
sqldf
的更为SQL-y的东西在一起很自在,您的输出的第3行应该是
Value=4
而不是
5
?谢谢您的帮助!是的,应该是4而不是5;我把数字弄得乱七八糟,忘了改变这个,但概念是一样的。