简体   繁体   English

R中的缩短向量(在data.frame内)多重化代码

[英]Shortening vectors (within a data.frame) mutiplication code in R

I have this code to do a series of multiplication and addition in R. Could someone give me a suggestion to use *apply to make it neater and shorter? 我有这段代码可以在R中进行一系列的乘法和加法运算。有人可以建议我使用* apply使它更整洁,更短吗?

I looked around with keywords such as "series", "multiplication" but did not get anywhere. 我环顾了诸如“系列”,“乘法”之类的关键字,但是却一无所获。 If this question has been posted before, please let me know the link. 如果此问题以前发布过,请让我知道链接。 Thank you. 谢谢。

df1n is a data.frame with >78 variables and 215 observation. df1n是一个data.frame具有> 78个变量和215个观察值。

dff[,3]<-(df1n[5]*((df1n[25]*df1n[26]*df1n[27]) + (df1n[28]*df1n[29]*df1n[30]) +
         (df1n[31]*df1n[32]*df1n[33]) + (df1n[34]*df1n[35]*df1n[36]) + 
         (df1n[37]*df1n[38]*df1n[39]) + (df1n[40]*df1n[41]*df1n[42]) +
         (df1n[61]*df1n[62]*df1n[63]) + (df1n[64]*df1n[65]*df1n[66]) + 
         (df1n[67]*df1n[68]*df1n[69]) + (df1n[70]*df1n[71]*df1n[72]) + 
         (df1n[73]*df1n[74]*df1n[75]) + (df1n[76]*df1n[77]*df1n[78]))
         )

Regards, ikel 问候,伊克尔

I'd use lapply() to construct a list of indices for each of the (A*B*C) pieces. 我将使用lapply()为每个(A*B*C)件构造一个索引列表。 Then, pass those indices to sapply , extracting each set of elements from df1n and multiplying them with prod() . 然后,将这些索引传递给sapply ,从df1n提取每组元素,然后将它们与prod()相乘。 The rest is self-explanatory: 其余的不言而喻:

df1n <- 1:100
ll <- lapply(c(seq(25, 40, by=3), seq(61, 76, by=3)), 
             function(X) seq(X, by=1, length.out=3))
df1n[5] * sum(sapply(ll, function(i) prod(df1n[i])))
# [1] 11439180

EDIT : Now that I know that each element of df1n is a length-215 vector, here's the code I'd suggest instead: 编辑 :现在,我知道df1n每个元素都是长度为215的向量,这是我建议的代码:

# Example data (a list in which each element is a vector of length 215).
x <- replicate(100, 1:215, simplify=FALSE) 
ll <- lapply(seq(25, 76, by=3), function(X) seq(X, by=1, length.out=3))
res <- x[[5]] * rowSums(sapply(ll, function(i) Reduce("*", x[i])))

str(res)
# num [1:215] 18 288 1458 4608 11250 ...

Here's a modification of Josh's solution that produces the same ouput as your original code on the sample data below. 这是对Josh解决方案的修改,该解决方案在以下示例数据上产生的输出与原始代码相同。

# Some sample data
df1n <- as.data.frame( lapply(1:80, function(i) seq(i, len=5)) )

df1n[5] * rowSums(sapply(c(seq(25,40,3), seq(61,76,3)), 
    function(i) df1n[[i]]*df1n[[i+1]]*df1n[[i+2]]))
#  c.5..6..7..8..9.
#1         11439180
#2         14386680
#3         17580528
#4         21032640
#5         24755220

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM