I need to add a column to a dataframe that reflects the information encoded in the rownames. The following is a minimal example illustrating the problem.
Example:
df <- data.frame(c(1,2,3,4),c(0,1,0,1))
colnames(df) <- c("Value","Ident")
rownames(df) <- c("fish1_101","fish1_102","fish2_103","fish2_104")
df
Encoded in the rownames is information about each sample. In this example the "fish1" prefix indicates salmon while the "fish2" prefix indicates sunfish.
I need to add a new column "fish_species" specifying the correct fish species.
Attempt:
key_df <- data.frame(c("fish1","fish2","fish3"),c("salmon","sunfish","halibut"))
colnames(key_df) <- c("key","species")
df["species"] <- apply(df, 1, function(x){
NameFound <- x[3]
NameFound_split <- unlist(strsplit(NameFound, "_"))
if (NameFound_split[1] == "fish1"){
out <- "salmon"
} else if (NameFound_split[1] == "fish2") {
out <- "sunfish"
} else if (NameFound_split[1] == "fish3") {
out <- "halibut"
}
return(out)
})
df <- df[,c(1,2,4)]
df # This is the desired result.
I am looking for a cleaner and more high throughput way to do this where an if statement isn't needed for each identity.