我正在尝试创建一个函数,它将结果的分数添加到我正在创建的数据框中,但是当我运行该函数时,它将数据框转换为一个值。我的代码如下所示:
library(dplyr)
strenght <- 0
endurance <- 0
precision <- 0
technique <- 0
speed <- 0
playerScore <- data.frame(strenght, endurance, precision, technique, speed)
test1 <- function(test1time, test1goal) {
if(test1time <= 1000) {
speed <- speed + 3.5
} else if(test1time >= 1001 & test1time <= 1350) {
speed <- speed + ((350 - (test1time - 1000))/100)
} else {
speed <- speed + 0
}
if(test1goal == 1){
precision <- precision + 0.5
} else {
precision <- precision + 0
}
}
playerScore <- test1(1025, 1)
首先,我创建了一个填充零值的数据框,因为尚未运行任何测试。然后我定义了第一个测试的函数。测试需要两个参数:玩家完成测试所用的秒数 (test1time) 和进球数 (test1goal)。
如果玩家在不到 10 秒的时间内完成测试,他应该在数据框中的速度得分上获得 3.5 分的奖励。高于此值的每 0.1 秒应从该分数中扣除 0.1 分(依此类推)。类似地,测试应该有效,如果玩家进球,他应该在数据框中获得 0.5 分的精确分数。
但是,我无法使代码工作 - 谁能帮我看看我哪里出错了?
编辑:想要的结果应该是:
> str(playerScore)
'data.frame': 1 obs. of 5 variables:
$ strenght : num 0
$ endurance: num 0
$ precision: num 0.5
$ technique: num 0
$ speed : num 3.25
但是,当我运行脚本时,结果是数据框“playerScore”被转换为值为 0.5 的值
尝试这样的事情,代码中的注释解释了原始代码的变化。
library(dplyr)
test1 <- function(test1time, test1goal) {
strenght <- 0
endurance <- 0
precision <- 0
technique <- 0
speed <- 0
if(test1time <= 1000) {
speed <- speed + 3.5
} else if(test1time >= 1001 & test1time <= 1350) {
speed <- speed + ((350 - (test1time - 1000))/100)
} else {
speed <- speed + 0
}
if(test1goal == 1){
precision <- precision + 0.5
} else {
precision <- precision + 0
}
return(data.frame(strenght, endurance, precision, technique, speed))
}
你的输出:
test1(1025, 1)
strenght endurance precision technique speed
1 0 0 0.5 0 3.25
现在,您可以随时将此信息添加到原始数据框中playerScore
,如下所示:
playerScore<-rbind(playerScore,test1(1025, 1))
playerScore<-rbind(playerScore,test1(1030, 8))
playerScore<-rbind(playerScore,test1(26, 1))
playerScore
strenght endurance precision technique speed
1 0 0 0.0 0 0.00
2 0 0 0.5 0 3.25
3 0 0 0.0 0 3.20
4 0 0 0.5 0 3.50
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句