引用一个数据帧对另一个数据帧进行分析



我有一个数据帧,我们把它命名为标题:

titles <- data.frame(V1=c("A", "B", "A", "B", "A", "A"))

我有另一个数据帧,stuff:

stuff <- data.frame(V1=c(1,2,3,4,5,6),
                    V2=c(10,20,30,40,50,60),
                    V3=c(1,3,5,7,9,11),
                    V4=c(2,4,6,8,10,12),
                    V5=c(9,8,7,6,5,4))

我想迭代,这样在每一列中,我乘以与A对应的所有行并乘以与B对应的行中的所有值

基本上……

对于"stuff"中的V1,我将乘以(1*3*5*6)因为它们对应于A

对于"stuff"中的V1,我将乘以(2*4),因为它们对应于B

我想在应用语句中为Stuff中的每一列执行此操作并输出结果。帮助吗?

一气之功:

sapply(split(stuff, titles$V1), sapply, prod)
#        A   B
#V1     90   8
#V2 900000 800
#V3    495  21
#V4   1440  32
#V5   1260  48

甚至:

by(stuff, titles$V1, sapply, prod)
#titles$V1: A
#    V1     V2     V3     V4     V5 
#    90 900000    495   1440   1260 
#---------------------------------------
#titles$V1: B
# V1  V2  V3  V4  V5 
#  8 800  21  32  48 

对于"A"行,我们可以使用

sapply(1:ncol(stuff), function(x) prod(stuff[titles$V1=="A",x]))
#[1]     90 900000    495   1440   1260

,相应地,对于"B"行

sapply(1:ncol(stuff), function(x) prod(stuff[titles$V1=="B",x]))
#[1]   8 800  21  32  48

使用data.table的选项。我们将data.frame转换为data。表' (setDT(stuff)),按'titles'中的'V1'列分组,我们在数据子集上循环(lapply(..)。表(.SD)和做乘法(prod)。

library(data.table)
setDT(stuff)[, lapply(.SD, prod), by = .(titles[['V1']])]
#   titles V1     V2  V3   V4   V5
#1:      A 90 900000 495 1440 1260
#2:      B  8    800  21   32   48

或类似的选项使用dplyrsummarise_each

library(dplyr)
stuff %>% 
      group_by(title=titles[['V1']])  %>%
      summarise_each(funs(prod))
#   title    V1     V2    V3    V4    V5
#   (fctr) (dbl)  (dbl) (dbl) (dbl) (dbl)
#1      A    90 900000   495  1440  1260
#2      B     8    800    21    32    48

最新更新