R新手,并努力充分利用它。这是一项每周需要完成多次的任务。
在工作中,我们得到了一个SAS代码文本文件,其中包含以下数据:
1,2,3,201,202,203 = "Screening"
101,102,301,302,404,405,1001= "Cycle 1 Day 1"
1002 = "Cycle 1 Day 2"
1003 = "Cycle 1 Day 3"
103,104,303,304,407,408,409,410 = "Cycle 1 Day 8"
105,106,305,306,412,413 = "Cycle 1 Day 15"
107,108,307,308,414,415,416,417,1022= "Cycle 1 Day 22"
1023 = "Cycle 1 Day 23"
1024 = "Cycle 1 Day 24"
109,110,309,310,418,419,420,421,2001 = "Cycle 2 Day 1"
2002= "Cycle 2 Day 2"
2003= "Cycle 2 Day 3"
111,112,422,423 = "Cycle 2 Day 8"
113,114,311,312,424,425 = "Cycle 2 Day 15"
115,116,426,427= "Cycle 2 Day 22"
117,118,119,313,314,315 = "Cycle 2 End of Cycle"
120,121,316,317,430,431 = "Cycle 3 Day 1"
122,123,432,433 = "Cycle 3 Day 8"
124,125,318,319,434,435 = "Cycle 3 Day 15"
126,127,436,437 = "Cycle 3 Day 22"
128,129,320,321,438,439 = "Cycle 4 Day 1"
我还有一个Excel文件,内容如下:
Visit No Vis Label
1 Screening Day -14 to -1
2 Screening Day -14 to -1
3 Screening Day -14 to -1
101 Cycle 1 Day 1 to 3
102 Cycle 1 Day 1 to 3
103 Cycle 1 Day 8
104 Cycle 1 Day 8
105 Cycle 1 Day 15
106 Cycle 1 Day 15
107 Cycle 1 Day 22
108 Cycle 1 Day 22
109 Cycle 2 Day 1
110 Cycle 2 Day 1
111 Cycle 2 Day 8
112 Cycle 2 Day 8
113 Cycle 2 Day 15
114 Cycle 2 Day 15
115 Cycle 2 Day 22
116 Cycle 2 Day 22
117 Cycle 2 End of Cycle
118 Cycle 2 End of Cycle
119 Cycle 2 End of Cycle
现在我必须将SAS代码txt文件与Excel文件进行比较,并记下SAS文件中缺少的代码。
我尝试读取SAS txt文件,该文件中充满了空白,并能够删除空白并通过以下方式获取内容:
d <- read.delim("testSAS.txt", sep = ":", strip.white = TRUE, skip = 2, header = FALSE)
结果是:
V1 V2
1 1,2,3,201,202,203 Screening
2 101,102,301,302,404,405,1001 Cycle 1 Day 1
3 1002 Cycle 1 Day 2
4 1003 Cycle 1 Day 3
5 103,104,303,304,407,408,409,410 Cycle 1 Day 8
6 105,106,305,306,412,413 Cycle 1 Day 15
现在,我想将V1值分开,这样每个值都会生成一个新的行,并附加相同的值,如下所示:
1 Screening
2 Screening
3 Screening
201 Screening
202 Screening
203 Screening
我使用了以下代码使其更具延展性,但它似乎返回了一个变形的列表:
df<- data.frame(matrix(unlist(d), nrow = 61, byrow = T),stringsAsFactors = FALSE)
现在想将其与Excel文件进行比较,以便最终生成一个txt或xlsx,说明哪些V1值不存在。
有没有比操作SAS txt文件更快的方法可以做到这一点?我该如何处理?从excel到txt的速度更快吗?反之亦然?
欢迎任何建议!
如果您的文件的格式为.ssa7bdat,则使用"haven"包读取sas文件,如下所示。为了读取xlsx文件,你可以使用openxlsx,它没有任何Java依赖关系,所以应该可以正常工作。请参阅下面的示例:
install.packages("haven")
library(haven)
sasfile <- haven::read_sas("path/to/sas/file.sas7bdat")
install.packages("openxlsx")
library(openxlsx)
xlsxfile <- openxlsx::read.xlsx(xlsxFile = "path/to/xlsx/file.xlsx")
编辑原始答案,现在我知道你想融化它。
为了以你想要的方式融化你的数据,我会做这样的
install.packages("stringr")
install.packages("plyr")
library(stringr)
library(plyr)
new_df <-plyr::ddply(df, .(V2),function(x) data.frame(V1=unlist(stringr::str_split(df$V1, pattern = ","))))
要根据需要重新排列列,可以执行
new_df <- new_df[,c("V1","V2")]
然后使用自定义构建的"dataCompareR"来比较R中的2个数据集
install.packages("dataCompareR")
dataCompareR::rCompare(dfA = sasfile,dfB = xlsxfile)
注意:我没有测试代码,所以请在评论中告诉我它是否有效。