在R中选择最大数值的行

时间:2018-09-29 16:15:19

标签: r

我有一个数据框,其中包含城市名称和投票百分比列以及其他字段。每个城市有不止一个候选人,每个候选人都有各自的投票份额,因此城市名称列包含1个城市的多行。没有获奖者专栏。因此,我想为此添加一列,以便可以对此进行分析。

我在编写一个功能时需要帮助,该功能要经过特定城市(多行)的候选人的投票份额,然后为投票份额最高的人分配值1。

数据框的图像:

enter image description here

在400多个城市中有近5000行。

2 个答案:

答案 0 :(得分:2)

这里是使用基数R的单行解决方案-

df <- data.frame(City = c("A", "A", "B", "B"),
                         Candidate = letters[23:26],
                         Votes = sample.int(1000, 4), stringsAsFactors = F)

df$Flag <- ave(df$Votes, df$City, FUN = function(x) x == max(x))

#      City Candidate Votes Flag
# 1    A         w    14    0
# 2    A         x   412    1
# 3    B         y    50    0
# 4    B         z   969    1

答案 1 :(得分:1)

data.table非常容易,因为它可以通过by很好地分组。可重现的示例:

R> suppressMessages(library(data.table))
R> set.seed(123)        # make it reproducible
R> N <- 100             # arbitrary
R> x <- data.table(city=sample(LETTERS, N, replace=TRUE), vote=runif(N, 0, 100))
R> setkey(x, city)      # for sorted display and faster access, but not required
R> head(x, 12)
    city    vote
 1:    A 52.1136
 2:    A 74.6568
 3:    B 89.0350
 4:    B 95.4091
 5:    B 84.7453
 6:    C 72.0596
 7:    C 35.3905
 8:    C 58.1750
 9:    C 59.4343
10:    C 65.9230
11:    D 69.0007
12:    D 31.1702
R>

现在我们有了数据,实际任务是单线的:

R> x[, high := vote==max(vote), by=city]   # assign vote==max(vote) by city
R>
R> head(x, 12)
    city    vote  high
 1:    A 52.1136 FALSE
 2:    A 74.6568  TRUE
 3:    B 89.0350 FALSE
 4:    B 95.4091  TRUE
 5:    B 84.7453 FALSE
 6:    C 72.0596  TRUE
 7:    C 35.3905 FALSE
 8:    C 58.1750 FALSE
 9:    C 59.4343 FALSE
10:    C 65.9230 FALSE
11:    D 69.0007 FALSE
12:    D 31.1702 FALSE
R> 

这使用布尔值作为“是否是最大值”比较的结果,如果您确实需要一个整数,则可以将其强制转换为

R> x[, high:=NULL]  # remove first as we change type
R> x[, high := as.integer(vote==max(vote)), by=city]
R> head(x,12)
    city    vote high
 1:    A 52.1136    0
 2:    A 74.6568    1
 3:    B 89.0350    0
 4:    B 95.4091    1
 5:    B 84.7453    0
 6:    C 72.0596    1
 7:    C 35.3905    0
 8:    C 58.1750    0
 9:    C 59.4343    0
10:    C 65.9230    0
11:    D 69.0007    0
12:    D 31.1702    0
R> 

编辑:我的表达过于复杂,已经简化。

相关问题