# R

#### Get an overview of a df

```r
library(skimr)
skim(your_df)
```

#### Change all factor to character

```r
i = sapply(df, is.factor) 
df[i] = lapply(df[i], as.character)
```

#### Change all column to character

```r
df[] = lapply(df, as.character)
```

#### String split

```r
library(stringr)
df$names = str_split_fixed(df$Name, ".01A.", 2)
```

#### String replacement

```r
library(stringr)
df$Country = str_replace_all(df$Country,"pattern","expect_string")
```

#### Get high frequent obs

```r
df_high_freq = data.frame(sort(table(df$feature), decreasing=T))
```

#### Remove a column

```r
drops = c("yes", "no")
df = df[ , !(names(df) %in% drops)]
```

#### Sort by a feature

```r
df = df[order(df[,feature]), ]
```

#### Remove rows contains string

```r
df = df[!grepl("REVERSE", df$Name),]
```

#### Remove #obs less than 5 group for two features

```r
library(dplyr)
df <- df %>% group_by_at(c(f1, f2)) %>% filter(n() >= 5)
```

#### Remove duplicate row

```r
df = df[!duplicated(df[c(f1, f2)]),]
```

#### Change value based on condition

```r
df$twohouses <- ifelse(df$data>=2, 2, 1)
```

#### Replace all 0 with na

```r
df[df == 0] = NA
```

#### Rename a column

```r
colnames(df)[colnames(df)=="old_name"] <- "new_name"
```

#### Sort by specific order

```r
df$animal <- factor(df$animal, levels = c("dog", "elephant","cat"))
df$color <- factor(df$color, levels = c("green", "blue", "red"))
df = df[order(df$animal,df$color),]
```

#### Rename multiple columns

```r
df = data.table::setnames(df, old = c('a','d'), new = c('anew','dnew'))
```

#### Remove NA like observations

```r
library(dplyr)
df = filter_all(df, all_vars(!grepl('Unknow|unknown|Unknown',.)))
```

#### Add a vector as the first column

```r
library(tibble)
df = add_column(df, vec, .before=1)
```

#### Change DataFrame from wide to long

```r
library(tidyr)
df_long = gather(df, "vars", "values", all_columns_except_ID)
```

#### Change DataFrame from long to wide

```r
library(tidyr)
df= spread(df_long, "vars", "values")
```

#### Remove rows that all var equals to 0

```r
library(dplyr)
filter_all(df, any_vars(. != 0))
```

#### Remove columns that all value is NA

```r
df <- df[,colSums(is.na(df))<nrow(df)]
```

#### Try catch syntax

```r
result = tryCatch({
    expr
}, warning = function(w) {
    warning-handler-code
}, error = function(e) {
    error-handler-code
}, finally = {
    cleanup-code
}
```

Filter dataframe with multiple condition

```r
df <- df[ which( df$V1 > 2 | df$V2 < 4) , ]
```

#### Generate a series of string

```r
aseries = sprintf("a%d", 1:5)
```

#### concatenating elements in a vector

```r
paste(sdata, collapse = '')
```

#### get difference for each row

```r
df = data.frame(group = rep(c(1, 2), each = 3), value = c(10,20,25,5,10,15))
df = df %>% group_by(group) %>% mutate(Diff = value - lag(value))
```

#### set java home

```r
Sys.setenv(JAVA_HOME="C:\Users\Jason\.jdks\corretto-1.8.0_282")
```

#### extract all matches of a pattern from a string

```r
sample_names = unique(str_extract_all(lib_str, "D3019_[0-9]+\\.MS[0-9]+")[[1]])
```

#### find duplicated occurrence

```
n_occur <- data.frame(table(vocabulary$id))
vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]
```

#### replace value in vector

```r
replace(x, x==0, 1)
```

#### assign gradient color in a range

```
FeaturePlot(scRNA_obj, features = target_gene)+
    scale_color_gradientn(colors = c("grey", "red", "red"), values = c(0,0.6,1))
```

#### png short cut

```
png(paste0("master_figure_british_columbia.png"), 
    width = 26, height = 20, units = "in", res = 300)
```

#### find string between 2 special chars

```
str_match(my_string, "char1\\s*(.*?)\\s*char2")[,2]
```

#### dplyr spread based on two columns assignment

```
DEGs_long = DEGs[,c("cluster", "gene")]
DEGs_long = DEGs_long %>% group_by(cluster) %>%
  mutate(id = row_number())
DEGs_wide= spread(DEGs_long, "cluster", "gene", fill=NA)
```

#### ggplot2 aes programmatically

```
plot_descriptives3 <- function(data, var) {
  
  var_enquo <- sym(var)
  
  data %>% 
    ggplot(aes(x = !!var_enquo)) +
    geom_histogram()
}

plot_descriptives3(mtcars, "hp")
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://juechen-yang.gitbook.io/juechen-s-codebook/master.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
