【问题标题】:Operation with data frame with loop for使用带有循环的数据框进行操作
【发布时间】:2016-01-14 10:31:50
【问题描述】:

我有这两个数据框:df(A) (nrow=10,ncol=2) 和 df(B) (nrow=3,ncol=2)。

 df(A)                    df(B)
col1  col2            col1 col2                     
1      2                13  34 
3      5                22  56 
5      7                30  42 
6      9                 
9      11                 
4.5   5.5                 
21    6.7                 
3.5   5                   
6     7.9                 
67     4                  

在这种模式下是否可以将 df(A) 中的每个值相乘和相加? :
示例:

A[1,1]*B[1,1] + A[1,1]*B[1,2] + A[1,1]*B[1,3]= 1*13+1*22+1*30= 65 
A[2,1]*B[1,1] + A[2,1]*B[1,2] + A[2,1]*B[1,3]= 3*13+3*22+3*30 = 195
and so on for all row in A&col1 for B$col1

A$col2 和 B$col2 相同

A[1,2]*B[1,1] + A[1,2]*B[1,2] + A[1,2]*B[1,3]= 2*34+2*56+2*42= 264
A[2,2]*B[1,1] + A[2,2]*B[1,2] + A[2,2]*B[1,3]= 5*34+5*56+5*42=660
and so on for all row in A&col2 for B$col2

预期的结果是df(C),有 2 列和 10 行。

我对@9​​87654327@ 很感兴趣,但它适用于整行或整列。这个例子是简化的,但我真正的df 是最大的,有10 列和1000 多行。 循环 for 有可能吗? 我以这种方式尝试循环for

temp <- rep(NA,3)

my_matrix <- matrix(0,ncol=ncol(A),nrow=nrow(A))

for (i in 1:nrow(A)){
  for (j in 1:3){
    temp(j) <- A(i+j-1)*B(i+j-1)
  }
  my_matrix(i) <- sum(temp)
}

但是 R 回复 :Error: could not find function "A"or

attempt to apply non-function`

提前谢谢你。

【问题讨论】:

  • 请显示预期输出
  • 您能更好地解释一下您的意思吗?是否要根据 A$col3 和 B$col3 中的条件将 A$col1 * B$col1 相乘。
  • 我编辑了我以前的帖子,现在我希望问题更好更清晰。如果你能帮助我提前谢谢你

标签: r loops dataframe


【解决方案1】:

我可能完全错了,但我会这样做:

1) 创建所有组合的网格

Grid&lt;-expand.grid(1:5,1:5)

编辑:匹配您对“相反产品”的定义

2) 根据感兴趣的值对数据框进行子集化

result<-matrix()
for(i in 1:nrow(Grid)){
   First<-A[A[,3]==Grid[i,1],1]*B[B[,3]==4-Grid[i,2],1] ### Gets the first column product, and does the "Contrary product" that you mention in comments
   Second<-A[A[,3]==Grid[i,1],2]*B[B[,3]==4-Grid[i,2],2] ### Gets the second column product
   result<-rbind(result,cbind(First,Second,Grid[i,1],Grid[i,2])) ### Keep track of the values you used for subsetting
}

【讨论】:

  • 嗨,我编辑了我以前的帖子,现在我希望问题更好更清晰。如果你能帮助我提前谢谢你。
  • 我认为您在新代码中弄错了行和行:数据框 B 只有 2 列,但您在示例中使用了“B[1,3]”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
  • 2022-08-10
相关资源
最近更新 更多