用R格式化电子表格时出现问题,如何使用R读写表格



我在大学里第一次和R一起上课。前言:我知道的还不够多,不知道什么,所以如果以前有人问过我这个问题,我很抱歉。我正在努力预测2020年德克萨斯州众议院选举的结果,我认为最好的预测是2018年州众议院选举。有150场比赛,所以我不能全部手工输入,但我找不到任何电子表格的数据格式符合我的要求。我希望它是一个非常标准的表格格式:我想要的表格格式。然而,我收到的国务卿的表格如下:丑陋的桌子。

我写了一些伪代码:这是Psuedo代码,基本上我们想构建一个新的CSV:

""%首先,我们想找到一个地区,房屋竞赛之前总是有一行破折号,所以我需要这样的函数:

Create a New CSV;
for(x=1; x<151 ; x +=1){
Assign x to the cell under the district number cloumn;
Find "---------------" ;
Go down one line;
Go over two lines;
% We should now be in the third column and now want to read in which party got how many votes. The number of parties is not consistant, so we need to account for uncontested races, libertarians, greens, and write ins. I want totals for Republicans, Democrats, and Other.
while(cell is not empty){
Party <- function which reads cell (but I want to read a string);
go right one column;
Votes <- function which reads cell (but I want to read an integer);
if(Party = Rep){
put this data in place in new CSV;
else if (Party = Dem)
put this data in place in new CSV;
else
OtherVote += Votes;
};
};
Assign OtherVote to the column for other party;
OtherVote <- 0;
%Now I want to assign 0 to null cells (ones where no rep, or no Dem, or no other party contested
read through single row 4 spaces, if its null assign it 0;
Party <- null
};'''

但我不知道该怎么做!以下是我需要帮助的内容:我可以在Rstudio中创建一个新的CSV吗?如何读取表中的特定单元格,并希望进行索引?最后,我该如何在R的桌子上写信呢?任何帮助都将不胜感激!非常感谢。

我可以在Rstudio中创建一个新的CSV吗?

可以。使用"write.csv"功能。

write.csv(df, file = "df.csv")#有关详细信息,请参阅帮助。

如何读取表中的特定单元格?

在df后面使用括号,示例如下。

df <- data.frame(x = c(1,2,3),  y = c("A","B","C"), z = c(15,25,35))
df[1,1]
#[1] 1
df[1,1:2]
#  x y
#1 1 A

如何在R中写入表?

如果要在xlsx中写入表,请使用openxlsx包中的函数write.xlsx

Wikipedia似乎有一个更接近您想要的格式的表。为了找到您要找的桌子,我们需要几个步骤:

  1. 从维基百科下载数据并提取表格
  2. 清理桌子
  3. 选择列
  4. 计算利润

1.从维基百科下载数据并提取表

rvest表有助于将网站下载并解析为R对象。首先我们下载整个网站的HTML。

library(dplyr)
library(rvest)
wiki_html <-
read_html(
"https://en.wikipedia.org/wiki/2018_United_States_House_of_Representatives_elections_in_Texas"
)

在这种情况下,有几种方法可以从HTML文件中获取特定对象我专门寻找类名为"wikitable planrowheaders sortable"的表,正如我从检查代码中了解到的那样,具有该类的唯一表是我们想要提取的。

library(purrr)
html_nodes(wiki_html, "table") %>%
map_lgl( ~ html_attr(., "class") == "wikitable plainrowheaders sortable") %>%
which()
#> [1] 20

然后我们可以选择表编号20,并将其转换为具有html_table()的数据帧

raw_table <-
html_nodes(wiki_html, "table")[[20]] %>%
html_table(fill = TRUE)

2.清理桌子

该表有重复的名称,我们可以通过使用as_tibble()及其.name_repair参数来更改。然后我们使用dplyr::select()来获取列。此外,我们使用dplyr::filter()来删除前两行,这两行在District列中的值为"District"。现在列仍然是characters矢量,但我们需要它们是numeric,因此我们首先从中删除逗号所有列,然后将列2到4转换为数字。

clean_table <-
raw_table %>%
as_tibble(.name_repair = "unique") %>%
filter(District != "District") %>%
mutate_all( ~ gsub(",", "", .)) %>%
mutate_at(2:4, as.numeric)

3.选择列和4。计算利润

我们使用dplyr::select()来选择您感兴趣的列,并为它们提供更有用的名称。最后,我们通过首先将选票相加来计算民主党和共和党选票之间的差距作为CCD_ 14,然后将差值除以CCD_。

clean_table %>%
select(District,
RepVote = Republican...2,
DemVote = Democratic...4,
OthVote = Others...6) %>%
mutate(
total_votes = RepVote + DemVote,
margin = abs(RepVote - DemVote) / total_votes * 100
)
#> # A tibble: 37 x 6
#>    District    RepVote DemVote OthVote total_votes margin
#>    <chr>         <dbl>   <dbl> <chr>         <dbl>  <dbl>
#>  1 District 1   168165   61263 3292         229428  46.6 
#>  2 District 2   139188  119992 4212         259180   7.41
#>  3 District 3   169520  138234 4604         307754  10.2 
#>  4 District 4   188667   57400 3178         246067  53.3 
#>  5 District 5   130617   78666 224          209283  24.8 
#>  6 District 6   135961  116350 3731         252311   7.77
#>  7 District 7   115642  127959 0            243601   5.06
#>  8 District 8   200619   67930 4621         268549  49.4 
#>  9 District 9        0  136256 16745        136256 100   
#> 10 District 10  157166  144034 6627         301200   4.36
#> # … with 27 more rows

编辑:如果你想使用国家提供的数据,在我看来,你要查找的数据就好像在第一列、第三列和第四列。所以你想做的是。

(下面的所有代码都没有经过测试,因为我没有原始数据。(

将数据读入R

library(readr)
tx18 <- read_csv("filename.csv")

选择相关列

tx18 <- tx18 %>%
select(c(1,3,4))

清洁工作台

tx18 <- tx18 %>%
filter(!is.na(X3),
X3 != "Party",
X3 != "Race Total")

按各方对数据进行分组和汇总

tx18 <- tx18 %>% 
group_by(X3) %>%
summarise(votes = sum(X3))

将数据透视/重塑为宽格式

tx18 %>$ 
pivot_wider(names_from = X3,
values_from = votes)

在这之后,你可以像我对维基百科数据所做的那样计算边际。

最新更新