如何减去DataFrame中的元素
How to subtract elements in a DataFrame
在 SparkR 中,我有一个 DataFrame data
包含 id
、amount_spent
和 amount_won
。
例如 id=1 我们有
head(filter(data, data$id==1))
输出为
1 30 10
1 40 100
1 22 80
1 14 2
到目前为止我想知道固定id 是否赢多于输。金额可以忽略不计。
在 R 中,我可以到达 运行,但这需要时间。假设我们有 100 个 ID。在 R 中我已经这样做了
w=c()
for(j in 1:100){
# Making it local for a fixed id
q=collect(filter(data, data$id==j))
# Checking the difference. 1 means wins and 0 means losses
if( as.numeric(q$amount_won) - as.numeric(q$amount_spent)>0 {
w[j]=1
}
else{w[j]=0}
}
现在 w 只为所有 ID 提供 1 和 0。在 sparkR 中,我想以更快的方式执行此操作。
我不确定这是否正是您想要的,所以请随时要求调整。
df <- data.frame(id = c(1,1,1,1),
amount_spent = c(30,40,22,14),
amount_won = c(10,100,80,2))
DF <- createDataFrame(sqlContext, df)
DF <- withColumn(DF, "won", DF$amount_won > DF$amount_spent)
DF$won <- cast(DF$won, "integer")
grouped <- groupBy(DF, DF$id)
aggregated <- agg(grouped, total_won = sum(DF$won), total_games = n(DF$won))
result <- withColumn(aggregated, "percentage_won" , aggregated$total_won/aggregated$total_games)
collect(result)
我在 DF 中添加了一列,是否该 ID 赢得的金额超过他在该行上花费的金额。结果输出某人玩的游戏数量、他赢得的游戏数量和他赢得游戏的百分比。
在 SparkR 中,我有一个 DataFrame data
包含 id
、amount_spent
和 amount_won
。
例如 id=1 我们有
head(filter(data, data$id==1))
输出为
1 30 10
1 40 100
1 22 80
1 14 2
到目前为止我想知道固定id 是否赢多于输。金额可以忽略不计。
在 R 中,我可以到达 运行,但这需要时间。假设我们有 100 个 ID。在 R 中我已经这样做了
w=c()
for(j in 1:100){
# Making it local for a fixed id
q=collect(filter(data, data$id==j))
# Checking the difference. 1 means wins and 0 means losses
if( as.numeric(q$amount_won) - as.numeric(q$amount_spent)>0 {
w[j]=1
}
else{w[j]=0}
}
现在 w 只为所有 ID 提供 1 和 0。在 sparkR 中,我想以更快的方式执行此操作。
我不确定这是否正是您想要的,所以请随时要求调整。
df <- data.frame(id = c(1,1,1,1),
amount_spent = c(30,40,22,14),
amount_won = c(10,100,80,2))
DF <- createDataFrame(sqlContext, df)
DF <- withColumn(DF, "won", DF$amount_won > DF$amount_spent)
DF$won <- cast(DF$won, "integer")
grouped <- groupBy(DF, DF$id)
aggregated <- agg(grouped, total_won = sum(DF$won), total_games = n(DF$won))
result <- withColumn(aggregated, "percentage_won" , aggregated$total_won/aggregated$total_games)
collect(result)
我在 DF 中添加了一列,是否该 ID 赢得的金额超过他在该行上花费的金额。结果输出某人玩的游戏数量、他赢得的游戏数量和他赢得游戏的百分比。