我有一个文本文件,包括一些数值,括号和逗号,如下所示:
[123,5],[345,21],[1567,34],[7689,234],....
所有数据都在一行中。
我需要从这个文本文件中提取这些数字,并且需要定义两个变量,如X
和Y
,这样括号中的所有第一个元素都保存在变量X中,所有第二个元素都保存在变量中是的。我还想在excel文件中包含这两个变量X
和Y
。
答案 0 :(得分:1)
假设您有一个名为# INITIALIZE LIST WITH DATE SEQUENCE DF
newldf <- list(data.frame(Date = as.factor(seq(as.POSIXct("2016-10-01", tz = "UTC"),
as.POSIXct("2016-10-31", tz = "UTC"),
by = 'day'))))
# APPEND LIST OF DATA FRAMES THAT ARE READ IN, EACH WITH SECOND COL = 1
newldf <- append(newldf,
list(data.frame(Date = c("2016-10-01", "2016-10-02",
"2016-10-03", "2016-10-04"), A = 1),
data.frame(Date = c("2016-10-07", "2016-10-08",
"2016-10-09"), B = 1),
data.frame(Date = c("2016-10-15", "2016-10-16",
"2016-10-17", "2016-10-18", "2016-10-19"), C=1)))
# MERGE ALL DATA FAMES TOGETHER
newDF <- Reduce(function(...) merge(..., by=c("Date"), all=T), newldf)
newDF[is.na(newDF)] <- 0 # CONVERT NAs TO ZEROs
newDF$Date <- as.POSIXct(newDF$Date, tz = "UTC") # CONVERT DATE TO POSIXct
str(newDF)
# 'data.frame': 31 obs. of 4 variables:
# $ Date: POSIXct, format: "2016-10-01" "2016-10-02" ...
# $ A : num 1 1 1 0 0 0 0 0 0 0 ...
# $ B : num 0 0 0 0 0 0 1 1 1 0 ...
# $ C : num 0 0 0 0 0 0 0 0 0 0 ...
str(DF)
# 'data.frame': 31 obs. of 4 variables:
# $ Date: POSIXct, format: "2016-10-01" "2016-10-02" ...
# $ A : num 1 1 1 0 0 0 0 0 0 0 ...
# $ B : num 0 0 0 0 0 0 1 1 1 0 ...
# $ C : num 0 0 0 0 0 0 0 0 0 0 ...
all.equal(DF, newDF)
# [1] TRUE
的文件,您可以执行以下操作:
file.txt