【问题标题】:R read csv with observations in columsR读取csv并在列中观察
【发布时间】:2019-05-25 15:19:13
【问题描述】:

到目前为止,在我在 R 中读取 csv 文件的每个示例中,变量都在列中,而观察值(个人)在行中。在我正在学习的介绍性统计课程中,有一个示例表,其中(许多)变量位于行中,(少数)观察值位于列中。有没有办法读取这样的表格,以便获得通常“方向”的数据框?

【问题讨论】:

  • 读取数据后使用t()
  • 在没有看到您的数据或代码或到目前为止您已经能够做到的情况下,除了猜测之外,很难做任何事情。 See here 制作可重现的示例

标签: r variables read.csv


【解决方案1】:

这是一个使用 tidyverse 的解决方案。首先,我们将数据收集成窄格式的整洁数据,然后将其展开回宽格式,通过将第一列从gather() 中排除,将第一列设置为收集观察的键。

我们将使用来自U.S. Census Bureau 的州级摘要数据来演示该技术。

我为四个州创建了一个人口数据表,其中州(观察)在列中,变量在表的行中列出。

为了使示例可重现,我们将数据输入 Excel 并将其保存为逗号分隔值文件,我们将其分配给 R 中的向量并使用read.csv() 读取。

textFile <- "Variable,Georgia,California,Alaska,Alabama
population2018Estimate,10519475,39557045,737438,4887871
population2010EstimatedBase,9688709,37254523,710249,4780138
pctChange2010to2018,8.6,6.2,3.8,2.3
population2010Census,8676653,37253956,710231,4779736"

# load tidyverse libraries 
library(tidyr)
library(dplyr)
# first gather to narrow format then spread back to wide format
data %>% 
     gather(.,state,value,-Variable) %>% spread(Variable,value)

...和结果:

       state pctChange2010to2018 population2010Census
1    Alabama                 2.3              4779736
2     Alaska                 3.8               710231
3 California                 6.2             37253956
4    Georgia                 8.6              8676653
  population2010EstimatedBase population2018Estimate
1                     4780138                4887871
2                      710249                 737438
3                    37254523               39557045
4                     9688709               10519475

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多