我试图在R中写一个脚本来读取一个只有与之共享的人才能访问的Google电子表格。该电子表格也在一个共享驱动器中(只有与它共享的人可以访问)。我知道googlespreadsheets包,但不知道如何处理读取私人电子表格。
谢谢你的帮助
在Google Sheet经常变化的情况下,直接从Google中获取最新的内容比手动提取CSV文件要好。
我们可以使用 googlesheets4
包来访问需要认证的Google Sheets电子表格。
例如,我将读取存储在Google上的Pokémon Stats电子表格。我们将通过 gs4_auth()
函数,获得一个电子表格列表,这样我们就可以通过 id
,然后阅读神奇宝贝统计表的第一个工作表。
library(googlesheets4)
# change next line to google account you need to access
# Respond to message in R console, then a browser window
# will open for you to complete the authentication process
gs4_auth(email = "[email protected]")
theSheets <-gs4_find()
这时就可以打印出 theSheets
来找到要下载的表。
> theSheets
# A tibble: 1 x 3
name id drive_resource
* <chr> <chr> <list>
1 PokemonStats <------------redacted----------------------> <named list [34]>
现在我们可以使用 theSheets$id
访问电子表格,通过 sheets_read()
功能。
pokemonData <- sheets_read(theSheets$id[1],sheet = 1)
head(pokemonData)
...和输出。
> pokemonData <- sheets_read(theSheets$id[1],sheet = 1)
Reading from "PokemonStats"
Range "'Pokemon'"
> head(pokemonData)
# A tibble: 6 x 13
Number Name Type1 Type2 Total HP Attack Defense SpecialAtk SpecialDef Speed Generation Legendary
<dbl> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 1 Bulbasaur Grass Poison 318 45 49 49 65 65 45 1 FALSE
2 2 Ivysaur Grass Poison 405 60 62 63 80 80 60 1 FALSE
3 3 Venusaur Grass Poison 525 80 82 83 100 100 80 1 FALSE
4 3 VenusaurMega Venusaur Grass Poison 625 80 100 123 122 120 80 1 FALSE
5 4 Charmander Fire NA 309 39 52 43 60 50 65 1 FALSE
6 5 Charmeleon Fire NA 405 58 64 58 80 65 80 1 FALSE
为了验证与我的账户共享的工作表可以通过以下方式访问 gs4_find()
,我创建了一个名为 TestSpreadsheet
并与本次答题所用的谷歌账号共享。
> theSheets <-gs4_find()
> theSheets
# A tibble: 2 x 3
name id drive_resource
* <chr> <chr> <list>
1 TestSpreadsheet <------------redacted----------------------> <named list [34]>
2 PokemonStats <------------redacted----------------------> <named list [34]>
要阅读该表,我们通过以下方式访问它 id
.
theId <- theSheets$id[theSheets$name == "TestSpreadsheet"]
testData <- sheets_read(theId,sheet = 1)
testData
...和输出。
> testData <- sheets_read(theId,sheet = 1)
Reading from "TestSpreadsheet"
Range "'Sheet1'"
> testData
# A tibble: 10 x 2
`Column 1` `Column 2`
<dbl> <dbl>
1 1 20
2 2 30
3 3 40
4 4 50
5 5 60
6 6 70
7 7 80
8 8 90
9 9 100
10 10 110
>
在谷歌表:
在顶部点击 "文件"。发布到网络
发布选项。选择 "csv "文件
点击发布
复制URL
并尝试下面的代码。
library(RCurl)
url <- getURL("URL You Copied")
file <- textConnection(url)
data <- read.csv(file)