[英]Format data in R
I have a excel file that contains data in the following format: 我有一个Excel文件,其中包含以下格式的数据:
Serial Name College Time
Wednesday 24/10/2014
1 StudentA UA 12:00:00
2 StudentB UA 13:00:00
Thursday 25/10/2014
3 StudentC UA 11:00:00
4 StudentA UA 15:00:00
When converted to CSV, it looks like this: 转换为CSV时,如下所示:
Wednesday,24/10/2014,,
1,StudentA,UA,12:00:00
2,StudentB,UA,13:00:00
So, basically, the data is sectioned into a per-day basis. 因此,基本上,数据按天划分。 The data for Wednesday, 24/10/2014 is preceded by a row containing Wednesday 24/10/2014 and the same for each day. 2014年10月24日星期三的数据之前有一行,其中包含2014年10月24日星期三,且每天的数据相同。 I want to convert this format to the following: 我想将此格式转换为以下格式:
Serial Name College Date Time
1 StudentA UA 24/10/2014 12:00:00
2 StudentB UA 24/10/2014 13:00:00
3 StudentC UA 25/10/2014 11:00:00
4 StudentA UA 25/10/2014 15:00:00
Feel free to ask any questions and use any tools/technologies. 随时提出任何问题并使用任何工具/技术。 I would prefer R, though, since I'm familiar with it. 不过,我更喜欢R,因为我对此很熟悉。
This is a very messy format, but here's one way to possibly deal with it. 这是一种非常凌乱的格式,但这是一种可能的处理方式。 First, just read in the raw lines, then partition the lines depending on special values 首先,只需读取原始行,然后根据特殊值对行进行分区
rr <- readLines("input.csv")
rr <- rr[nchar(rr)>0] #remove empty lines
ghead <- grepl(",,", rr) # find the "headers" by looking for two empty columns
glines <- rle(cumsum(ghead [-1]))$lengths-1 #see how many rows each group has
#read header and details lines separately
dd <- read.csv(text=rr[!ghead ])
gg <- read.csv(text=rr[ghead ], header=F,
col.names=c("Weekday","Date","X","Y"),
colClasses=c("character","character","NULL","NULL"))
#merge together
cbind(dd, gg[rep(1:nrow(gg), glines),])
And this produces 这产生了
Serial Name College Time Weekday Date
1 1 StudentA UA 12:00:00 Wednesday 24/10/2014
1.1 2 StudentB UA 13:00:00 Wednesday 24/10/2014
2 3 StudentC UA 11:00:00 Thursday 25/10/2014
2.1 4 StudentA UA 15:00:00 Thursday 25/10/2014
Here's an approach that uses read.mtable
from my GitHub-only "SOfun" package . 下面是一个使用的方法read.mtable
从我的GitHub上,只有“SOfun”包 。
## Load SOfun (or just copy and paste the required function)
library(SOfun) ## For `read.mtable`
library(data.table) ## for setnames and rbindlist
## Reads in each chunk as a data.frame in a list
X <- read.mtable("test.csv", chunkId = ",,$", sep = ",")
## Create a vector of new column names
colNames <- c("Serial", "Name", "College", "Time", "Date")
rbindlist(
lapply(
## The next line adds the dates back in
Map(cbind, X, lapply(strsplit(names(X), ","), `[`, 2)),
setnames, colNames))
# Serial Name College Time Date
# 1: 1 StudentA UA 12:00:00 PM 24/10/2014
# 2: 2 StudentB UA 01:00:00 PM 24/10/2014
# 3: 3 StudentC UA 11:00:00 AM 25/10/2014
# 4: 4 StudentA UA 03:00:00 PM 25/10/2014
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.