1.如何选择某几列,将非NA的值转换为1

 
library(dplyr)
 
# 创建模拟数据
protein_data <- tibble(
	Protein_ID = paste0("Protein_", 1:10),
	Gene_Name = c("TP53", "BRCA1", "EGFR", "AKT1", "MAPK1", "CDK2", "MYC", "PTEN", "NFKB1", "STAT3"),
	Description = c("Tumor suppressor", "DNA repair", "Receptor kinase", "Serine/threonine kinase", 
					"Signal transduction", "Cell cycle regulator", "Transcription factor", 
					"Phosphatase", "Transcription factor", "Signal transducer"),
	Molecular_Weight = round(runif(10, 20, 200), 1),
	Sample_A = c(1.2, NA, 3.4, 0.5, NA, 2.1, NA, 0.8, 1.9, NA),
	Sample_B = c(NA, 2.3, 1.1, NA, 4.0, NA, 0.7, 1.5, NA, 3.2),
	Sample_C = c(0.9, 1.8, NA, 2.2, NA, NA, 1.0, NA, 2.5, 0.4),
	Sample_D = c(2.5, NA, 0.6, 1.7, 3.3, NA, NA, 0.2, 1.1, NA),
	Sample_E = c(NA, 1.4, 2.8, NA, 0.9, 1.6, NA, 3.0, NA, 0.7)
)
 
protein_data <- protein_data %>%
	mutate(across(5:9, ~ ifelse(!is.na(.), 1, NA)))

2.如何重命名列名?

 
# 原始列名
colnames <- c(
	"TotalQuantity.raw.file1", 
	"TotalQuantity.raw.file2", 
	"Intensity.raw.file1", 
	"Score.raw.file2"
)
 
# 替换字典:将.raw.file1 → _rep1,.raw.file2 → _rep2
dict <- c(
	"TotalQuantity.raw.file1" = "_rep1",
	".raw.file2" = "_rep2"
)
 
 
library(stringr)
 
rename_by_dict <- function(colnames, dict) {
	str_replace_all(colnames, dict)
}
 
new_colnames <- rename_by_dict(colnames, dict)

3.如何给不同的组合设置颜色

#方法1
 mod_colors <- list(
     Phosphorylation = "#8dd3c7",
     Acetylation = "#ffffb3",
     Ubiquitination = "#bebada",
     Methylation = "#fb8072"
 )
  ggsci::pal_npg()(4)"#E64B35FF" "#4DBBD5FF" "#00A087FF" "#3C5488FF"
#方法2
 
mod_names <- c("Phosphorylation", "Acetylation", "Ubiquitination", "Methylation")
mod_colors <- setNames(ggsci::pal_npg()(4)[seq_along(mod_names)], mod_names)
 

4.如何找出所有重复的行?

library(dplyr)
 
df1 <- tibble(
	PG.ProteinGroups = c("P1", "P2", "P1", "P3", "P2", "P4"),
	EG.ProteinPTMLocations = c("K100", "S200", "K100", "T300", "S200", "Y500"),
	Intensity = c(100, 200, 300, 400, 500, 600)
)
 
 
dup <- df1 %>%  
	filter(
		duplicated(across(c(PG.ProteinGroups, EG.ProteinPTMLocations))) |
			duplicated(across(c(PG.ProteinGroups, EG.ProteinPTMLocations)), fromLast = TRUE)
	)
 

5.如何将氨基酸的修饰和位置拆开比如K100拆分为K和100 两列?

 
df <- tibble(site_pos = c("K100", "S253", "T31"))
#方法1
df[c("Amino acid", "Position")] <- str_split_fixed(df$site_pos, "", n = 2)
#方法2
df %>% mutate(
	site = gsub("\\d+", "", site_pos),
	position = gsub("[A-Z]", "", site_pos),
)