我有一个excel数据集(保存为csv),它有3列和数千行数据。我需要重新组织这些数据,以便某些数据在某些增量中重复。为了举例说明,假设我有以下三列标题的数据:
X-Y-Z 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
(FYI -这些数据只是为了说明性的目的而组成的)我的目标是通过复制一定数量的行(比如一次4行),然后一个接一个地插入这些数据,从而创建一种交错的效果。因此,如果对上面的示例数据执行此操作,您将不会复制第1-4行,而是首先复制第2-5行,然后在第4行之后插入。对于原始的第3-6行,然后是原始的第4-7行,等等,直到我们不能复制/插入4行的全部增量(在这种情况下,当我们到达第7-10行时):
X-Y-Z 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
(FYI:我只使用粗体和斜体来强调)
我不想在R中做这件事--如果这可以在Excel中完成(或者其他任何程序),我会很高兴听到这样做的。考虑到这些excel文件的大小,手动复制/插入是完全不可行的。我猜可以用某种for循环吗?
谢谢!
发布于 2014-07-21 20:07:23
这对于您的示例(假设您的数据位于一个名为my.data的矩阵或数据框架中)是可行的:
my.data[ as.vector( mapply(1:7, 4:10, FUN='seq') ), ]然后只需要更改7和10来表示数据(可能是nrow(my.data)-3和nrow(my.data))。
发布于 2014-07-29 19:14:40
看来我想出了个解决办法。下面是代码:
## 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 (i.e. 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 #####https://stackoverflow.com/questions/24873447
复制相似问题