r - 当数据未格式化为表格时将数据导入 R 中

标签 r dataframe read.table

我有以下制表符分隔的 .txt 文件,包含 9796 行:

https://www.dropbox.com/s/fnrbmaw8odm2rqs/Kommunale_N%C3%B8gletal.txt?dl=0

我想将该文件读入 R,但该文件不是经典的表格格式。相反,每个感兴趣的变量都有 279 行和 16 列,其中第一行定义变量名称,前 2 列定义城市名称和代码,后面的 14 列定义 1993-2006 年。每个变量由空行分隔。该文件包含 35 个变量。

我想将数据读入 data.frame,但其中一列用于城市名称、城市代码和年份,一列用于 35 个变量中的每一个。

如果您不习惯点击链接或更喜欢较小的样本,下面说明了数据集(2 个变量和 3 年的观察):

Indbyggertal 1 januar
Københavns Kommune     101    466129    467253  471300
Frederiksberg Kommune  147    87173     87466   88002
Ballerup Kommune       151    45427     45293   45356

Andel 0-17-årige
Københavns Kommune     101    14.0      14.1    14.4
Frederiksberg Kommune  147    12.4      12.5    12.6
Ballerup Kommune       151    21.2      21.1    21.3

首选输出的前 3 行应如下所示:

Municipality name      Municipality code    Year    Indbyggertal 1 januar   Andel 0-17-årige    …   Ældreudg (netto) pr 65+/67+-årig
Københavns Kommune     101                  1993    466129                  14                      35350
Frederiksberg Kommune  147                  1993    87173                   12.4                    33701
Ballerup Kommune       151                  1993    45427                   21.2                    31126

最佳答案

可能有更多方法可以做到这一点,但我下面使用的技巧是以文本形式读取所有数据,然后确定新 block 开始的位置,最后循环读取所有 block 并将它们存储在列表:

lines <- readLines("Kommunale_Nøgletal.txt", encoding = "latin1")

# Find empty lines; these start a new block
start <- c(0, grep("^[\t]+$", lines))

# Read titles
headers <- lines[start + 1]
headers <- gsub("\t", "", headers)

# Determine beginnen and ending of data blocks
begin <- start + 2
end   <- c(start[-1]-1, length(lines))

# Read each of the data blocks into a list
data <- vector(mode = "list", length(headers))
for (i in seq_along(headers)) {
  block <- lines[begin[i]:end[i]]
  data[[i]] <- read.table(textConnection(block), sep="\t", na.strings=c("U","M","-"))
}
names(data) <- headers

在此之后,在每个数据集中设置正确的 header 应该很简单,然后将其合并到一个数据帧中。可以使用 dplyr 包中的 rbind_all 来完成。下面是一个例子:

# Set columnnames in data
# Add variable name to data
for (i in names(data)) {
  names(data[[i]]) <- c("municipality", "code", paste0("Y", 1993:2006))
  data[[i]]$var = i
}

# Merge the different datasets into one data.frame
library(dplyr)
data <- rbind_all(data)

# Transpose the data
library(reshape2)
m <- melt(data, id.vars = c("municipality", "code", "var"))
res <- dcast(m, municipality + code + variable ~ var)

# Fix the year variable
names(res)[3] <- "year"
res$year <- as.numeric(gsub("Y", "", res$year))

关于r - 当数据未格式化为表格时将数据导入 R 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153195/

相关文章:

r - 为什么 cSplit 返回 TRUE 而不是字符

string - 如何使用函数的参数作为变量的名称?

python - 为什么 Python 内存使用量会在一段时间后下降?

在 R 中读取固定宽度格式的文件

r - 访问 R : read. table.ffdf 中的大型 csv 速度变慢

r - tcltk 对话框出现在 RStudio/Shiny Windows 下

r - 在 `dplyr` 中,当使用 `pivot_wide` 时,我想同时替换 'NA'

python - 如何在 pandas 数据帧上优化双 for 循环?

python - Python中基于列名的Dataframe到List of List的转换

R 中的 read.table 和评论