按列划分的数据子集,在R中具有等效值
我遇到了一个问题,即如何根据一个条件对数据进行子集划分,其中一行对列变量的观察值等于同一行中不同列变量的观察值 我正在处理的例子是选举中的投票按列划分的数据子集,在R中具有等效值,r,R,我遇到了一个问题,即如何根据一个条件对数据进行子集划分,其中一行对列变量的观察值等于同一行中不同列变量的观察值 我正在处理的例子是选举中的投票 library(dplyr) library(tidyverse) library(ggplot2) library(matrixStats) Candidate1Votes <- c(45, 18, 34) Candidate2Votes <- c(43, 52, 33) Candidate3Votes <- c(12, 30, 3
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)
我想知道哪个候选人在每个选区赢得最多的选票(因此我生成了行最大值):
我已将其转换为数据帧以供进一步使用:
election.df <- as.data.frame(election.matrix)
election.df作为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
库(dplyr)
选举:1.df%
过滤器(Candiate1==获奖者)
#选区冠军1选区冠军2选区冠军3选区冠军
#
# 1 1 45 43 12 45
# 2 3 34 33 33 34
作为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
库(dplyr)
选举:1.df%
过滤器(Candiate1==获奖者)
#选区冠军1选区冠军2选区冠军3选区冠军
#
# 1 1 45 43 12 45
# 2 3 34 33 33 34
库(dplyr)
election.df库(dplyr)
election.dfsubset(election.df,Candidate1==选区Twinners)
subset(election.df,Candidate1==选区Twinners)
此操作将不会运行。不支持tibble()。您可以通过添加library(dplyr)
或library(tibble)
来解决此问题。您是对的,我运行了您的回复以查看其是否有效,并且我已预加载了库。此操作将不会运行。不支持tibble()。您可以通过添加library(dplyr)
或library(tibble)
来解决此问题。您是对的,我运行了您的回复以查看其是否有效,并已预加载了库
election.df <- as.data.frame(election.matrix)
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
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,]