【问题标题】:Alteration of two values in R Dataframe更改 R Dataframe 中的两个值
【发布时间】:2020-04-06 09:52:30
【问题描述】:

最初我有前四列。第 1 轮和第 2 轮有两个玩家 A 和 B。每轮最高得分为 1。

在第五列(我想要得到的)中,我想知道玩家 A 在第二轮中与初始分数相比有多少变化(分数变化)。

这样,在第 3 行,对于第 2 轮,B 有 0.855,A 有 (1-0.855)=0.145。其中,A与初始分数的变化为-0.855。

示例数据由此生成: '''

set.seed(123)
Round1 <- sample("A", size=10, replace = T, prob = NULL)
Score1 <- sample(seq(0.71,1,length.out = 3), size=10, replace = T, prob = NULL)
Score2 <- sample(seq(0.71,1,length.out = 3),size = 10, replace = T)
Round2 <- sample(LETTERS[1:2],size = 10,replace = T)
d <- data.frame(Round1,Score1,Round2,Score2)

谁能帮我写得更好? 我试过了,但并没有真正达到我的预期:

d$Alteration <- ifelse(d$Round1==d$Round2, -1*(d$Score1-d$Score2),ifelse(d$Round1!=d$Round2 & d$Score2==1, -1+d$Score1, -1*d$Score2))

【问题讨论】:

  • 请在您的问题中添加预期的输出。
  • 你是如何计算Alteration列的?
  • 预期输出如第五列“alteration”,我试图通过最后一行的命令解决它,但没有给出我的预期。
  • 好的,但是正如@RonakShah 所问的那样,也许是在解释你使用的数学,想象你是用好的旧钢笔和铅笔做的;那会是什么样子>
  • 正如我在上面试图解释的:这样,在第 3 行,对于第 2 轮,B 有 0.855,A 有 (1-0.855)=0.145。其中,A 与初始分数的变化为-0.855。因为在第一轮 A 有 1,而在第二轮它有 0.145。所以,对于 A,score1+alteration=score2 等于 1+(-0.855)=0.145

标签: r dataframe comparison string-comparison


【解决方案1】:

为了从 score1 中获取更改,我只使用 ifelse 函数创建了两个中间列。如果 round1 和 round2 具有相同的值,则 col A 用于 score2。如果round1 和round2 具有不同的值,则col B 是round2 中A 的当前分数。然后,A 从 score1 到 score2 的变化计算如下

set.seed(123)
Round1 <- sample("A", size=10, replace = T, prob = NULL)
Score1 <- sample(1, size=10, replace = T, prob = NULL)
Score2 <- sample(seq(0.71,1,length.out = 3),size = 10, replace = T)
Round2 <- sample(LETTERS[1:2],size = 10,replace = T)
d <- data.frame(Round1,Score1,Round2,Score2)
d$Round1  <- as.character(d$Round1)
d$Round2 <- as.character(d$Round2)
d$A <- ifelse(d$Round1==d$Round2, d$Score2, 0)
d$B <- ifelse(d$Round1!=d$Round2, 1-d$Score2, 0)
d$Alteration <- ifelse(d$A!=0, d$A-d$Score1, d$B-d$Score1)
d

前六个输出:

>Round1 Score1 Round2 Score2     A     B Alteration
> A     1.000      B  1.000   0.000 0.000 -1.000
> A     0.855      B  1.000   0.000 0.000 -0.855
> A     1.000      B  0.855   0.000 0.145 -0.855
> A     0.855      B  1.000   0.000 0.000 -0.855
> A     0.710      A  0.855   0.855 0.000  0.145
> A     1.000      A  1.000   1.000 0.000  0.000

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多