thanks a lot for your answer! do you think is possible to embed these 3 operations in a function and apply this function to a list of n dataframes?
• 0 views
•
link
Hey all, i have a technical problem. i have a 2 column table with a list of GO and respective p-value in R. Now i want to add another column based on a specific pattern in the GO term. e.g. if the GO term starts with GO:002* (for capturing e.g. GO:002545545,GO:002434343, GO:00254457,etc..) i want to add "yes" to the third column, otherwise "no". Does someone know how to do this in R? thanks in advance
Given that you have a dataframe termed df which has two columns, use grepl() to find your pattern:
# add a blank third column
df[,3] <- NA
# fill "yes" if column 1 contains the pattern:
df[grepl("GO:002", df[,1]),3] <- c("yes")
# and "no" if not => simple use !grepl() as the opposite to grepl() :
df[!grepl("GO:002", df[,1]),3] <- c("no")
thanks a lot for your answer! do you think is possible to embed these 3 operations in a function and apply this function to a list of n dataframes?
Yep, something like:
findreplace<-function(df)
{
df[,3] <- NA
df[grepl("GO:002", df[,1]),3] <- c("yes")
df[!grepl("GO:002", df[,1]),3] <- c("no")
df
}
list_of_df <- list(df1,df2,df3)
fixed_list <- lapply(list_of_df,findreplace)
Log in to answer this question.
I dont understand exactly the pattern but following is the code snippet: add_col <- c() df #data.frame containing the two columns for(i in df[,1]) { if(i matches pattern) add_col <- c(add_col, 'yes') else add_col <- c(add_col, 'no') } cbind(df, add_col)
If pattern is clear I can perhaps write a more proper if.