## 

```{r}
library(tximport)

# setup the folder and filenames to read
folders <- dir(pattern="SRR21568*")
samples <- sub("_quant", "", folders)
files <- file.path( folders, "abundance.h5" )
names(files) <- samples

txi.kallisto <- tximport(files, type = "kallisto", txOut = TRUE)
```

```{r}
head(txi.kallisto$counts)
```


```{r}
colSums(txi.kallisto$counts)
```

```{r}
sum(rowSums(txi.kallisto$counts)>0)
```

```{r}
to.keep <- rowSums(txi.kallisto$counts) > 0
kset.nonzero <- txi.kallisto$counts[to.keep,]
```

```{r}
keep2 <- apply(kset.nonzero,1,sd)>0
x <- kset.nonzero[keep2,]
```

## Principal Component Analysis

```{r}
pca <- prcomp(t(x), scale=TRUE)
```

```{r}
summary(pca)
```



```{r}
plot(pca$x[,1], pca$x[,2],
     col=c("blue","blue","red","red"),
     xlab="PC1", ylab="PC2", pch=16)
```

> Q. Use ggplot to make a similar figure of PC1 vs PC2 and a seperate figure PC1 vs PC3 and PC2 vs PC3.


```{r}
library(ggplot2)

pc_df <- as.data.frame(pca$x)
pc_df$sample <- rownames(pc_df)

# Assign groups based on sample names
pc_df$group <- ifelse(grepl("SRR2156848|SRR2156849", pc_df$sample),
                      "Control",
                      "CRISPR")

```


```{r}
ggplot(pc_df, aes(x = PC1, y = PC3, color = group, label = sample)) +
  geom_point(size = 4) +
  geom_text(vjust = -0.7, size = 3) +
  scale_color_manual(values = c("Control"="blue", "CRISPR"="red")) +
  theme_bw() +
  labs(title = "PC1 vs PC3",
      x = "PC1",
       y = "PC3",
       color = "Group")


```

```{r}
ggplot(pc_df, aes(x = PC2, y = PC3, color = group, label = sample)) +
  geom_point(size = 4) +
  geom_text(vjust = -0.7, size = 3) +
  scale_color_manual(values = c("Control"="blue", "CRISPR"="red")) +
  theme_bw() +
  labs(title = "PC2 vs PC3",
       x = "PC2",
       y = "PC3",
       color = "Group")

```






