簡體   English   中英

如何在R中將其余行賦給單個列

[英]How to assigh the rest of row to a single column in R

假設我們有一個內容為someFile的文件:

date time data
2015-02-28 09:00:00,173 Some data here
2015-02-28 09:10:00,251 Anoter data here

我考慮使用read.table

read.table("someFile", header=T, sep=" ")

我不知道如何將行尾(“此處有一些數據”字符串)分配給單列

您可以使用readLines讀取文件,使用替換字符串前面的空格,然后嘗試使用read.table

dat1 <- read.table(text=sub('(?<=\\d) (?=[A-Za-z])', ',',
  lines[-1], perl=TRUE), header=FALSE, stringsAsFactors=FALSE, sep=",")
colnames(dat1) <-  c('datetime', 'Val', 'Col2')
dat1
#             datetime Val             Col2
#1 2015-02-28 09:00:00 173   Some data here
#2 2015-02-28 09:10:00 251 Anoter data here

數據

lines <- readLines('SomeFile.txt') 

由於定界符不一致(您有“,”和“”定界符),因此必須(至少)進行兩次。 有幾種選擇,但是在我看來,這是最適應和最易讀的選擇:

1)將整個文件導入為字符串列表:

   datRaw <- readLines("someFile")[[1]]

2)解析它,手動定義格式。

   Parser <- function(line){
                        initSplit <- strsplit(line,"[ ,]")[[1]]
                        firstCol <- initSplit[1]
                        sndCol <- initSplit[2]
                        thirdCol <- strsplit(line,",")[[1]][2]
                        return(c(firstCol,sndCol,thirdCol))
                     }   
   dat <- as.data.frame(t(sapply(datRaw[-1],Parser)))
   names(dat) <- strsplit(datRaw[1]," ")[[1]]


    dat
                                                    date     time
     2015-02-28 09:00:00,173 Some data here   2015-02-28 09:00:00
     2015-02-28 09:10:00,251 Anoter data here 2015-02-28 09:10:00
                                                              data
     2015-02-28 09:00:00,173 Some data here     173 Some data here
     2015-02-28 09:10:00,251 Anoter data here 251 Anoter data here

首先,看起來您的“數據”列正在使用空格(因為它是字符串)。 如果要支持此功能,則需要將分隔符更改為其他內容,例如逗號:

date,time,number,data
2015-02-28,09:00:00,173,Some data here
2015-02-28,09:10:00,251,Another data here

...和:

> read.table(someFile, header=T, sep=",")

現在,它可以正確讀取。

您可以使用$column讀取特定的列,並利用as.vector將“數據”列作為向量:

> mydata <- as.vector(read.table(someFile, header=TRUE, sep=",")$data)
> mydata
[1] "Some data here"    "Another data here"
> mydata[1]
[1] "Some data here"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM