用R来读取和重组excel数据

我有一个Excel数据集(保存为csv),有3列和数千行数据。 我需要重新组织这些数据,使其中的一些以某种增量重复。 为了说明,说我有一个三列标题下面的数据:

XYZ

1 5 2

2 18 23

3 9 25

4 10 32

5 11 34

6 23 24

7 89 54

8 25 12

9 24 10

10 3 11

(仅供参考)我的目标是通过复制一些行(如每次4行)重新组织这些数据,然后将它们一个接一个地插入,从而产生交错的效果。 所以如果我们这样做了上面的示例数据,您不会复制第1-4行,而是首先复制第2-5行,然后将其插入第4行。这将重复原始行3-6,然后原始行4-7等,直到不能再复制/插入4行的整个增量(在这种情况下,当我们击到第7-10行时)实际上:

XYZ

1 5 2

2 18 23

3 9 25

4 10 32

2 18 23

3 9 25

4 10 32

5 11 34

3 9 25

4 10 32

5 11 34

6 23 24

4 10 32

5 11 34

6 23 24

7 89 54

5 11 34

6 23 24

7 89 54

8 25 12

6 23 24

7 89 54

8 25 12

9 24 10

7 89 54

8 25 12

9 24 10

10 3 11

(仅供参考:我只使用粗体斜体

我不会在R中这样做 – 如果这可以在Excel(或其他任何程序)中完成,我会很乐意听到。 考虑到这些excel文件的大小,我手动复制/插入是不可行的。 我猜测某种for循环可以使用?

谢谢!

这应该为你工作(假设你的数据是在一个名为my.data的matrix或数据框中):

 my.data[ as.vector( mapply(1:7, 4:10, FUN='seq') ), ] 

你只需要改变7和10来表示你的数据(可能是nrow(my.data)-3nrow(my.data) )。

看起来我能够找出一个解决scheme。 代码如下:

 ## Import Data from CSV ## require(xlsx) require(rJava) ogdata <- read.table("dataupload.csv", header = TRUE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "") str(ogdata) ##Add x, the cut off for ogdata ## x<-nrow(ogdata) ## Manipulate ogdata to add day and hour columns ## require(lubridate) require(methods) dates<-as.POSIXlt(ogdata$Time) ogdata$hour<-hour(dates) ogdata$day<-mday(ogdata$Time) ############## FOR LOOPS!!! ################ # counts a<-1 b<-720 #anchor anchorFrame<-data.frame((ogdata[a:b, "hour"]), (ogdata[a:b, "Value"])) #the for loop should be indexed in a sequenced where it goes from 0 to x-30, # moving up by 24 (ie one day at a time) a=a+24 b=b+24 for (i in seq(from=25, to=(x-30), by=24)) { tframes<-data.frame((ogdata[a:b, "hour"]), (ogdata[a:b, "Value"])) anchorFrame<-rbind(anchorFrame, tframes) a=a+24 b=b+24 } ##Create new counter for anchorFrame y<-nrow(anchorFrame) lineNumber<-c(seq(1:y)) ## Create a Day 'For loop' daylinenumber<-c(seq(1:(30*24))) Day<-data.frame(c(ceiling(daylinenumber/24))) for (i in seq(from=721, to=(y), by=720)) { nextmonthofdays<-data.frame(c(ceiling(daylinenumber/24))) Day<-rbind(Day, nextmonthofdays) } ## Create "t," or the variable known as "Time Frame" anchorFrame$t<-c(ceiling(lineNumber/720)) ## Bind columns in the correct order FinalSet<-cbind(Day, anchorFrame) ## Give column header the correct names colnames(FinalSet)<-c("Day", "Hour", "Value", "time") #### Export data as a csv #####