数据框计算-基本减法

时间:2018-09-18 12:37:49

标签: r dataframe

我有一个如下数据框:

student  Marks_1   Marks_2
    A1      25      28
    B1      22      24
    C1      18      25

A列-学生, B列-Marks_1, C列-标记_2, 我想执行基本计算以根据以下公式获得分数。

A1_Score =(C2-B2)^2

获取错误消息:

  

“-”对因素没有意义

预期输出:

A1_score    9
B1_score    4
C1_score   49

3 个答案:

答案 0 :(得分:1)

尝试一下:

您的数据集:

    student Marks_1 Marks_2 score
1      A1      25      28     9
2      B1      22      24     4
3      C1      18      25    49

输出:

const data = [
    {modelNumber: "123456789", balance: { amount:1000, currency:"EUR" }},
    {modelNumber: "987654321", balance: { amount:2000, currency:"EUR" }},
    {modelNumber: "322353466", balance: { amount:1500, currency:"GBP" }},
    {modelNumber: "892347522", balance: { amount:1000, currency:"USD" }},
    {modelNumber: "931883113", balance: { amount:3000, currency:"INR" }},
    {modelNumber: "854300564", balance: { amount:2500, currency:"GBP" }},
    {modelNumber: "931883113", balance: { amount:3000, currency:"INR" }},
    {modelNumber: "854300564", balance: { amount:3500, currency:"USD" }}
];

const grouped = data.reduce((o, { balance: { amount:a, currency:c } }) =>
   ({...o, [c]: (o[c] || 0) + a }), {});

const result = Object.keys(grouped).map(currency =>
    ({currency, totalAmount: grouped[currency] }));

console.log(result);

答案 1 :(得分:1)

尝试以下代码以添加所需的其他列:

df$score=(df$Marks_1-df$Marks_2)^2
> df
  student Marks_1 Marks_2 score
1      A1      25      28        9
2      B1      22      24        4
3      C1      18      25       49

输入数据集:

df<-data.frame(student=c("A1","B1","C1"),
               Marks_1=c(25,22,18),
               Marks_2=c(28,24,25))

答案 2 :(得分:0)

使用data.table

df <- read.table(stringsAsFactors = TRUE,
  header = TRUE, text = 'student  Marks_1   Marks_2
A1      25      28
B1      22      24
C1      18      25')


library(data.table)

setDT(df)[,score:= (Marks_2-Marks_1)^2]
df

   student Marks_1 Marks_2 score
1:      A1      25      28     9
2:      B1      22      24     4
3:      C1      18      25    49