: OP. data.table:
df <- structure(list(Probe.Id = c("1418126_at", "145119_a_at", "1423477_at",
"1434193_at", "100_at"), Gene.Id = c("6352", "2192", NA,
"100506144///9204", "100506144///100506146///100506148///100506150"),
Score.d = c(28.52578, 24.87866, 24.43532, 6.22395, 6.22395)),
.Names = c("Probe.Id", "Gene.Id", "Score.d"), row.names = c(NA, 5L),
class = "data.frame")
require(data.table)
dt <- data.table(df)
dt.out <- dt[, list(Probe.Id = Probe.Id,
Gene.Id = unlist(strsplit(Gene.Id, "///")),
Score.d = Score.d), by=1:nrow(dt)]
> dt.out
# nrow Probe.Id Gene.Id Score.d
# 1: 1 1418126_at 6352 28.52578
# 2: 2 145119_a_at 2192 24.87866
# 3: 3 1423477_at NA 24.43532
# 4: 4 1434193_at 100506144 6.22395
# 5: 4 1434193_at 9204 6.22395
# 6: 5 100_at 100506144 6.22395
# 7: 5 100_at 100506146 6.22395
# 8: 5 100_at 100506148 6.22395
# 9: 5 100_at 100506150 6.22395
fixed = TRUE strsplit , /// - .
data.table. , strsplit Gene.Id , 1 ( data.table , , 2 :
dt[, Gene.Id_split := strsplit(dt$Gene.Id, "///", fixed=TRUE)]
dt.2 <- dt[, list(Probe.Id = Probe.Id,
Gene.Id = unlist(Gene.Id_split),
Score.d = Score.d), by = 1:nrow(dt)]
data.table, , , 295245. rbenchmark:
DT1 <- function() {
dt.1 <- dt[, list(Probe.Id = Probe.Id,
Gene.Id = unlist(strsplit(Gene.Id, "///", fixed = TRUE)),
Score.d = Score.d), by=1:nrow(dt)]
}
DT2 <- function() {
dt[, Gene.Id_split := strsplit(dt$Gene.Id, "///", fixed=TRUE)]
dt.2 <- dt[, list(Probe.Id = Probe.Id, Gene.Id = unlist(Gene.Id_split), Score.d = Score.d), by = 1:nrow(dt)]
}
require(rbenchmark)
benchmark(DT1(), DT2(), replications=10, order="elapsed")
1,6 . ///. , .
OLD-: ( )
: 1) find the positions, ///, 2) extract, 3) duplicate, 4) sub 5) combine them.
df <- structure(list(Probe.Id = structure(c(1L, 4L, 2L, 3L),
.Label = c("1418126_at", "1423477_at", "1434193_at", "145119_a_at"),
class = "factor"), Gene.Id = structure(c(3L, 2L, NA, 1L),
.Label = c("100506144///9204", "2192", "6352"), class = "factor"),
Score.d = c(28.52578, 24.87866, 24.43532, 6.22395)),
.Names = c("Probe.Id", "Gene.Id", "Score.d"),
class = "data.frame", row.names = c(NA, -4L))
idx <- grepl("[/]{3}", df$Gene.Id)
df1 <- df[!idx, ]
df2 <- df[idx, ]
df3 <- df2
4) sub
df2$Gene.Id <- sub("[/]{3}.*$", "", df2$Gene.Id)
df3$Gene.Id <- sub("^.*[/]{3}", "", df3$Gene.Id) # replace the beginning
# 5) combine/put them back
df.out <- rbind(df1, df2, df3)
# if necessary sort them here.