I am trying to call the str_split function for both columns (Proteins and Positions.within.proteins), and then concatenate the corresponding values in a new column called ID.
df <- data.frame(Proteins = c("Q99755;A2A3N6", "O00329", "O00444",
"O14965", "O14976", "Q6A1A2;O15530", "O43318", "O43526", "O43930;P51817",
"O60331"), Positions.within.proteins = c("276;223", "708", "41",
"162", "175", "84;111", "63", "628", "78;78", "270"))
Here are my codes.
my.function <- function(x, y){
protein.names <- str_split(x, ";")[[1]]
position.names <- str_split(y, ";")[[1]]
ID <- list()
for (i in 1:length(protein.names)){
ID[i] <- paste(protein.names[i], position.names[i], sep ="_")
}
ID.2 <- unlist(ID)
return(ID.2)
}
It works to some extent when I call the function on a single row.
row1 <- my.function(df$Proteins[1], df$Positions.within.proteins[1])
"Q99755_276" "A2A3N6_223"
But my questions are:
- How to apply this function to the whole data frame?
- How to convert
"Q99755_276" "A2A3N6_223"to what I want"Q99755_276;A2A3N6_223"
I'd like to use the apply function, but am not sure if the apply function can take two arguments.
Here shows what it should look like.
df.final <- data.frame(Proteins = c("Q99755;A2A3N6", "O00329", "O00444",
"O14965", "O14976", "Q6A1A2;O15530", "O43318", "O43526", "O43930;P51817",
"O60331"), Positions.within.proteins = c("276;223", "708", "41",
"162", "175", "84;111", "63", "628", "78;78", "270"), ID = c("Q99755_276;A2A3N6_223",
"O00329_708", "O00444_41", "O14965_162", "O14976_175", "Q6A1A2_84;O15530_111",
"O43318_63", "O43526_628", "O43930_78;P51817_78", "O60331_270"
))
Does anyone know how to achieve these? Thanks so much for any help!