循环或应用函数以运行具有不同变量的方程式

时间:2018-07-20 15:44:17

标签: r loops apply repeat

我正在尝试做一些我确定在R中确实很简单的事情。但是我无法弄清楚。我想运行相同的方程式6次,每次更改方程式中的变量。 我的数据是这样的:

[#Rename my data
mydata <- BSC_OnlineSurvey_Salient.Beliefs
summary (mydata)
View(mydata)

##Descriptive stats
sapply(mydata, mean, na.rm = TRUE)
sumstats <- sapply(mydata, mean, na.rm = TRUE)
sumstats

#1st: Rename columns
colnames (mydata)
colnames(mydata)=c("ID", "Understands restocking", "Restocking will increase the No. of crabs", "Increasing the No. of crabs is...", "Restocking will result in more crabs to catch", "More crabs to catch is...", "Restocking will result in more fishers fishing for crabs", "More fishers fishing for crabs is...", "Resocking will result in no change in abundance of crabs", "No change in the abundance of crabs is...","Restocking will increase the fishing pressure on crabs", "Increasing the fishing pressure on crabs is", "Restocking will have an impact on the environment and other species", "Having an impact on the environment and other species is...", "Overall views on restocking") 
View(mydata)

#Replace Belief evaluation (very unlikely to very likely) from -3-3 to 0-6
Eval1 <- mydata$`Restocking will increase the No. of crabs`
...#Done for 6 "Eval"
Eval1
Eval1\[Eval1 == 3\] <- 6
Eval1\[Eval1 == 2\] <- 5
Eval1\[Eval1 == 1\] <- 4
Eval1\[Eval1 == 0\] <- 3
Eval1\[Eval1 == -3\] <- 0
Eval1\[Eval1 == -2\] <- 1
Eval1\[Eval1 == -1\] <- 2

...
Strength1 <- mydata$`Increasing the No. of crabs is...`
Strength2 <- mydata$`More crabs to catch is...`
Strength3 <- mydata$`More fishers fishing for crabs is...`
...#Done for 6 "Strength"][1]

我不想写6次相同的简单方程式。我不知道该怎么做,我只是略有想法,可能是使用了应用f(x)之一或进行了循环...

我的数据Is a set of variables, Eval(1,2,3...) are on a scale from -3 to 3; Strength (1,2,3,..) are on a scale from 0 to 6

我想对每一行做叉积,然后求出每个叉积的均值: 评估1 *实力1 Eval2 * Strength2

理想情况下无需书写 crossprod1 <-平均值(Eval1 * Strength1,na.rm = TRUE) crossprod1

如果有人可以提供帮助,我将非常感谢! 干杯!

  [1]: https://i.stack.imgur.com/jH9Zs.png

1 个答案:

答案 0 :(得分:0)

希望这会给您一些想法。干杯!

meanTotals = c()
for(r in 1:nrow(dataset)){
  rowTotals = c()
  for(c in 1:ncol(dataset)/2){
    rowTotals = c(rowTotals, dataset[r, 2*c-1] * dataset[r, 2*c])
  }
  meanTotals = c(meanTotals, rowTotals)
}
mean(meanTotals)