我目前有一个以篮子格式设置的表,以便将不规则数量的数据与表的每一行相关联。如:
01,item1,item2,item3
02,item1,item2,
03,item1,item2,item3,item4
04,item1
但是,我需要将其更改为规范化的事务格式,每行只有一个项目。如:
01,item1
01,item2
01,item3
02,item1
02,item2
03,item1
......等等。是否有简单的自动或编程方式来执行此操作?数据目前在MySQL数据库中,我可以以各种文件类型导出,我也可以访问RStudio和Microsoft Excel来尝试这样做。我能为RStudio找到的所有事务资源都假设数据已经是第二种格式,这正是我想要的。
答案 0 :(得分:1)
我假设我理解了数据集在将其读入R后的样子,即它将是一个矩形数据框,其中填充了NA以使行具有相同的长度。所以这应该可以解决问题:
#Create your dataset (this step is not for you)
row1 = c("01","item1","item2","item3",NA)
row2 = c("02","item1","item2",NA,NA)
row3 = c("03","item1","item2","item3","item4")
row4 = c("04","item1",NA,NA,NA)
Data = rbind(row1,row2,row3,row4)
#Now do the reconstruction (this step is for you)
col1 = NULL
col2 = NULL
for(i in 1:nrow(Data)){
col1 = c(col1,rep(Data[i],ncol(Data)-1))
col2 = c(col2,Data[i,-1])
}
NewData = cbind(col1,col2)[!is.na(col2),]
所以,你得到的是以下
> Data
[,1] [,2] [,3] [,4] [,5]
row1 "01" "item1" "item2" "item3" NA
row2 "02" "item1" "item2" NA NA
row3 "03" "item1" "item2" "item3" "item4"
row4 "04" "item1" NA NA NA
>
> NewData
col1 col2
[1,] "01" "item1"
[2,] "01" "item2"
[3,] "01" "item3"
[4,] "02" "item1"
[5,] "02" "item2"
[6,] "03" "item1"
[7,] "03" "item2"
[8,] "03" "item3"
[9,] "03" "item4"
[10,] "04" "item1"
所以希望这会有所帮助。
答案 1 :(得分:0)
这个问题与one非常相似。正如@DWin在评论中提到的那样,您需要将paste( . , . sep=",")
应用于拆分列表。
xx <- read.table(text ='01,item1,item2,item3
02,item1,item2,
03,item1,item2,item3,item4
04,item1')
unlist(lapply(strsplit(as.character(xx$V1), ','),
function(x) paste(x[1],x[-1],sep=',')))
[1] "01,item1" "01,item2" "01,item3" "02,item1" "02,item2" "03,item1" "03,item2" "03,item3" "03,item4" "04,item1"