【问题标题】:Subset data by columns with equivalent values in R按 R 中具有等效值的列对数据进行子集
【发布时间】:2020-08-16 03:39:22
【问题描述】:

我遇到了一个问题,即如何根据行对列变量的观察值等于同一行中不同列变量的观察值的条件对数据进行子集化。

我在这里使用的示例是选举中的投票

library(dplyr)
library(tidyverse)
library(ggplot2)
library(matrixStats)

Candidate1Votes <- c(45, 18, 34)
Candidate2Votes <- c(43, 52, 33)
Candidate3Votes <- c(12, 30, 33)
Precinct <- c(1, 2, 3)
election.matrix <- cbind(Precinct, Candidate1Votes, Candidate2Votes,
                           Candidate3Votes)

这段代码得到一个这样的矩阵:

Precinct    Candidate1    Candidate2    Candidate3 
1           45             43             12
2           18             52             30
3           34             33             33

我想知道哪个候选人在每个选区赢得了最多的选票(因此我生成了逐行最大值):

PrecinctWinners <- rowMaxs(election.matrix)

我将它绑定到矩阵,使其现在看起来像这样:

Precinct    Candidate1    Candidate2    Candidate3    PrecinctWinners
1           45             43             12             45
2           18             52             30             52
3           34             33             33             34

我已将其转换为数据框以供进一步使用:

election.df <- as.data.frame(election.matrix)

这是我的问题。我想对候选人 1 获得多票的行的数据进行子集化(其中election.df$Candidate1 =election.df$PrecinctWinners)。如何创建子集条件,根据具有相同值的行中的两个不同观察结果来选择数据中的行?

【问题讨论】:

  • subset(election.df ,Candidate1==PrecinctWinners)

标签: r


【解决方案1】:

作为 Duck 评论中解决方案的替代方案,您可以按如下方式使用 dplyr:

library(dplyr)

election.df <- tibble(precint = c(1, 2, 3),
                      Candiate1 = c(45, 18, 34),
                      Candiate2 = c(43, 52, 33),
                      Candiate3 = c(12, 30, 33),
                      PrecintWinners = c(45, 52, 34))

election.df %>%
  filter(Candiate1 == PrecintWinners)


#   precint Candiate1 Candiate2 Candiate3 PrecintWinners
#     <dbl>     <dbl>     <dbl>     <dbl>          <dbl>
# 1       1        45        43        12             45
# 2       3        34        33        33             34

【讨论】:

    【解决方案2】:
    library(dplyr)
    
    election.df <- tibble(precint = c(1, 2, 3),
                          Candiate1 = c(45, 18, 34),
                          Candiate2 = c(43, 52, 33),
                          Candiate3 = c(12, 30, 33),
                          PrecintWinners = c(45, 52, 34))
    
    election = election.df[election.df$Candiate1 == election.df$PrecintWinners,]
    

    这将找到所述条件为真的行,然后选择相应的列

    【讨论】:

    • 这不会运行。不支持 tibble()。可以通过添加library(dplyr)library(tibble)来解决。
    • 你是对的,我运行了你的回复,看看是否有效,我已经预加载了库
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多