读取txt文件并将其转换为数据帧

时间:2019-11-26 08:38:54

标签: r date

我有一个.txt文件,其中包含一些投资数据。我想将文件中的数据转换为具有三列的数据框。 .txt文件中的数据如下所示。

Date:
06-04-15, 07-04-15, 08-04-15, 09-04-15, 10-04-15
Equity : 
-237.79, -170.37, 304.32, 54.19, -130.5
Debt : 
16318.49, 9543.76, 6421.67, 3590.47, 2386.3

2 个答案:

答案 0 :(得分:4)

如果您要使用read.table(),则以下内容可能会有所帮助:

假设dat.txt包含上述内容,然后

dat <- read.table("dat.txt",fill=T,sep = ",")
df <- as.data.frame(t(dat[seq(2,nrow(dat),by=2),]))
rownames(df) <- seq(nrow(df))
colnames(df) <- trimws(gsub(":","",dat[seq(1,nrow(dat),by=2),1]))

收益:

> df
       Date   Equity     Debt 
1  06-04-15  -237.79 16318.49
2  07-04-15  -170.37  9543.76
3  08-04-15   304.32  6421.67
4  09-04-15    54.19  3590.47
5  10-04-15   -130.5   2386.3

答案 1 :(得分:3)

假设文本文件名为demo.txt,这是执行此操作的一种方法

#Read the file line by line
all_vals <- readLines("demo.txt")
#Since the column names and data are in alternate lines
#We first gather column names together and clean them
column_names <- trimws(sub(":", "", all_vals[c(TRUE, FALSE)]))
#we can then paste the data part together and assign column names to it
df <- setNames(data.frame(t(read.table(text = paste0(all_vals[c(FALSE, TRUE)], 
       collapse = "\n"), sep = ",")), row.names = NULL), column_names)
#Since most of the data is read as factors, we use type.convert to 
#convert data in their respective format.
type.convert(df)

#       Date  Equity     Debt
#1  06-04-15 -237.79 16318.49
#2  07-04-15 -170.37  9543.76
#3  08-04-15  304.32  6421.67
#4  09-04-15   54.19  3590.47
#5  10-04-15 -130.50  2386.30