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 - Fatal编程技术网

基于主变量从R表中删除零

基于主变量从R表中删除零,r,R,我在R中有这个数据集 dd=data.frame( main=c("G","G","G","R","R","R","Y","Y","Y"),test=c(0,1,1,0,1,1,0,1,1), a = c(1,0,0,2,0,0,3,0,0), b= c(0,3,0,0,6,0,0,4,0), c=c(0,0,5,0,0,8,0,0,9)) 我想看起来像这样 main test a b c [1,] G 1 1 3 5 [2,] R 1 2 6 8 [3,] Y 1 3

我在R中有这个数据集

dd=data.frame(
main=c("G","G","G","R","R","R","Y","Y","Y"),test=c(0,1,1,0,1,1,0,1,1),
a = c(1,0,0,2,0,0,3,0,0), b= c(0,3,0,0,6,0,0,4,0), c=c(0,0,5,0,0,8,0,0,9))
我想看起来像这样

     main test a   b   c  
[1,] G 1 1 3 5
[2,] R 1 2 6 8
[3,] Y 1 3 4 9
我有一些代码,但它不能正常工作

你的帮助很合适

aggregate(.~main, aggregate(.~main+test, dd, sum), sum)
#  main test a b c
#1    G    1 1 3 5
#2    R    1 2 6 8
#3    Y    1 3 4 9
首先,我们通过主数据和测试进行聚合。有了这个聚合,我们就只能按主对象分组了。嵌套过程允许我们首先添加a、b、c列,然后我们可以在之后进行完全折叠

对于@AnandaMahto的data.table解决方案

as.data.table(dd)[, test := max(test), by = "main"][, lapply(.SD, sum), by = .(main, test)]
#   main test a b c
#1:    G    1 1 3 5
#2:    R    1 2 6 8
#3:    Y    1 3 4 9
此dplyr解决方案还包括:

dd %>% group_by(main) %>% summarise_each(funs(max))
#Source: local data frame [3 x 5]
#
#  main test a b c
#1    G    1 1 3 5
#2    R    1 2 6 8
#3    Y    1 3 4 9

这确实取决于你的最终产品。我很难看出将测试id与其他列一起添加会有什么帮助,但也许有一种方法可以让你发疯:

我认为我们可以在聚合中使用函数max,就像@Pierre Lafortune在dplyr解决方案中使用的那样

aggregate(. ~ main , data = dd, max)
输出:

  main test a b c
1    G    1 1 3 5
2    R    1 2 6 8
3    Y    1 3 4 9
sqldf:


测试列的规则是什么?对于其他人,你可以使用聚合。如果你能在不批评我的情况下提供帮助,并投票支持我而不是支持我学习,我真的很感激。要在这里学习,你有责任提出一个可回答的问题。正如皮埃尔在下面提供的那样,这只能通过一些专业知识和猜测来回答,因为你选择不在问题本身提供任何解释。如果我是你,我就不会为反对票而战;下次试着更好地表述你的问题。如果这个问题以前被问过,而我没有发现任何东西,我是新的R用户,也许如果你能更合理,提供链接,它不会伤害到我,而不是否决我的问题。这只是一个指标,我需要它在我的dataset@AnandaMahto或者data.tabledd[,lappy.SD,sum,by=.main,test=1+0*test]或setDTdcastmeltdd,id.vars=cmain,main~变量,sum[,test:=test/2][],尽管这些有点愚蠢:
library(sqldf)
sqldf("SELECT main, max(test) test, max(a) a, max(b) b, max(c) c 
      FROM dd 
      GROUP BY main")