0% found this document useful (0 votes)
4 views21 pages

R Data Analysis and Visualization Guide

The document provides instructions for installing R and RStudio, along with examples of data analysis using R, including reading Excel files, performing statistical tests, and creating visualizations with ggplot2. It covers various statistical methods such as t-tests, ANOVA, and non-parametric tests, as well as data plotting techniques. Additionally, it includes code snippets for data manipulation and analysis, demonstrating the use of libraries like readxl and ggplot2.

Uploaded by

cavadzadenaibe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

R Data Analysis and Visualization Guide

The document provides instructions for installing R and RStudio, along with examples of data analysis using R, including reading Excel files, performing statistical tests, and creating visualizations with ggplot2. It covers various statistical methods such as t-tests, ANOVA, and non-parametric tests, as well as data plotting techniques. Additionally, it includes code snippets for data manipulation and analysis, demonstrating the use of libraries like readxl and ggplot2.

Uploaded by

cavadzadenaibe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]

org/

[Link]

[Link]

[Link]

base Binaries for base distribution. This is what you want to install R for the first time.

Download R-4.3.2 for Windows (79 megabytes, 64 bit)

[Link]

[Link]

FIRST INSTALL R
choose yes for personal library

ALSO install readxl

library("readxl")

read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]")

read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]")
Results <- read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]")

Results <- read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]")

data <- read_excel("D:/OneDrive - Izmir Yuksek Teknoloji


Enstitusu/3_Dersler/MBG328DigitalCell/[Link]")

data <- [Link]("D:/OneDrive - Izmir Yuksek Teknoloji


Enstitusu/3_Dersler/MBG328DigitalCell/coding/[Link]")

[Link](data$Area)

[Link](n= NULL, delta=2000, sd=2000, [Link]=0.05,power=0.9)

[Link](n= 9, delta=NULL, sd=2000, [Link]=0.05,power=0.9)

#Always plot your data, two data with similar statistics can have different distribution. THIS WORKS IN
RSTUDIO

library(ggplot2) # need for R

data(anscombe)

show(anscombe)

summary(anscombe)

lm(y1~x1, data=anscombe)

lm(y2~x2, data=anscombe)

lm(y3~x3, data=anscombe)

lm(y4~x4, data=anscombe)

sapply(1:4,function(x) cor(anscombe [,x], anscombe [,x+4]))

sapply(5:8,function(x) var(anscombe [,x]))

library(ggplot2)

p1<-ggplot(anscombe) + geom_point(aes(x1,y1))

p1

p2<- ggplot(anscombe)+geom_point(aes(x2,y2))

p3<- ggplot(anscombe)+geom_point(aes(x3,y3))

p4<- ggplot(anscombe)+geom_point(aes(x4,y4))

p2
p3

p4

[Link](1) #initialize a pseudorandom number generator

data0<- rnorm(100)

plot(data0,t="p") #plotted as points

hist(data0)

qqnorm(data0, xlim=c(-3,3), ylim=c(-3,3), main="Normal Q-Q Plot",

xlab= "Theoretical Quantiles", ylab="Sample Quantiles", [Link]= TRUE)

abline(a=0,b=1,lty=2) #y=b*x+a lty is line type dashed or not

data <- [Link]

qqnorm(data$Area, xlim=c(-1000,1000), ylim=c(-1000,1000), main="Normal Q-Q Plot",

xlab= "Theoretical Quantiles", ylab="Sample Quantiles", [Link]= TRUE)

hist(data$Area)

qqnorm(book2$datax, xlim=c(-3,3), ylim=c(-3,3), main="Normal Q-Q Plot",

xlab= "Theoretical Quantiles", ylab="Sample Quantiles", [Link]= TRUE)

qqnorm(Results$Area, xlim=c(0,1000), ylim=c(0,1000), main="Normal Q-Q Plot",

xlab= "Theoretical Quantiles", ylab="Sample Quantiles", [Link]= TRUE)

abline(a=0,b=1,lty=2) #y=b*x+a lty is line type dashed or not

[Link](data0)
summary(data0)

sd(data0)

[Link](book2$datax)

[Link](data0,mu=1) #Does data0 have mean of 1?

[Link](data0,mu=0.1)

[Link](1)

data1<- rnorm(8, mean=1, sd=0.3)

data2<- rnorm(8, mean=3, sd=0.9)

plot(data1,t="p") # or data1plot <- plot(data1,t="p")

plot(data2,t="p") # or data2plot <- plot(data2,t="p")

[Link](data1, data2)

[Link](data1, data2, paired=FALSE, [Link]=FALSE)

#for non-normal data means wilcoxon

[Link](1)

data3<- rbeta(40,5,1)

data4<- rbeta(40,2,1)

[Link](data3,data4)

[Link](data3,data4, paired=TRUE)

[Link](data3,data4, paired=FALSE, [Link]=FALSE)

[Link](Results$Circ.,Results$Round)
#for non-normal data distributions kolmogorov-smirnov

[Link](data3,data4)

cdf3<- ecdf(data3) # generate cumulative distribution function cdf

cdf4<- ecdf(data4)

pdf("[Link]") # open a pdf file

plot(0,0, type="l", xlim=c(0,1), ylim=c(0,1), xlab="Circularity", ylab="Cumulative probability")

lines(cdf3,lwd=2)

lines(cdf4, col="gray", lwd=2)

legend("topleft", legend=c("data3", "data4"), bty="o", col=c("black","gray"), lwd=2, bg="white")

[Link]()

[Link](data3,data4)

cdf3<- ecdf(data3) # generate cumulative distribution function cdf

cdf4<- ecdf(data3)

pdf("[Link]") # open a pdf file

plot(0,0, type="l", xlim=c(0,1), ylim=c(0,1), xlab="Circularity", ylab="Cumulative probability")

lines(cdf3,lwd=4)

lines(cdf4, col="gray", lwd=2)

legend("topleft", legend=c("data3", "data4"), bty="o", col=c("black","gray"), lwd=2, bg="white")

[Link]()

[Link](data3,data33)

cdf3<- ecdf(data3) # generate cumulative distribution function cdf

cdf33<- ecdf(data33)

pdf("[Link]") # open a pdf file

plot(0,0, type="l", xlim=c(0,1), ylim=c(0,1), xlab="Circularity", ylab="Cumulative probability")

lines(cdf3,lwd=4)

lines(cdf33, col="gray", lwd=2)

legend("topleft", legend=c("data3", "data33"), bty="o", col=c("black","gray"), lwd=2, bg="white")


[Link]()

cdf1<- ecdf(data1) # generate cumulative distribution function cdf

cdf2<- ecdf(data2)

pdf("[Link]") # open a pdf file

plot(0,0, type="l", xlim=c(0,3), ylim=c(0,3), xlab="Circularity", ylab="Cumulative probability")

lines(cdf1,lwd=2)

lines(cdf2, col="gray", lwd=2)

legend("topleft", legend=c("data1", "data2"), bty="o", col=c("black","gray"), lwd=2, bg="white")

[Link]()

#for percent comparison

data5<-matrix(c(18,460,57,466), byrow=TRUE,2,2)

rownames(data5)=c("ctrl","rnai")

colnames(data5)=c("mitosis","interphase")

data5

[Link](data5)

data55<-matrix(c(18,460,17,466), byrow=TRUE,2,2)

rownames(data55)=c("ctrl","rnai")

colnames(data55)=c("mitosis","interphase")

data55

[Link](data55)
data6 <- [Link] (

signal=c(3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 2,

3, 3, 2, 3, 3, 2, 3, 3, 2),

condition = factor(rep(c("ctrl","sirna1","sirna2"),10)))

data6 # to see the data

data6_av <- aov(signal ~ condition, data6)

summary(data6_av)

-----

TELLS US THERE IS A SIGNIFICANT DIFFERENCE THAT DEPENDS ON THE "condition" VARIABLE

Df Sum Sq Mean Sq F value Pr(>F)

condition 2 6.667 3.333 3.45e+31 <2e-16 ***

Residuals 27 0.000 0.000

Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

-----

data6_tukey <- TukeyHSD(data6_av) #HSD Honestly significant difference

data6_tukey

TESTS ALL THE PAIRWISE COMBINATIONS

------Bütün data alt alta olunca ok ama kendisi çoklu sütun okumadı------

value <- read_excel("E:/_Rprogramming/[Link]")

View(value)

library(readxl)
group <- read_excel("E:/_Rprogramming/[Link]")

View(group)

dpo <- [Link](v=value, g=group) #burada x ve y birleşiyor, excellerden birinde x diğerinde y var tüm
veriler altalta

View(dpo)

dpo_av<- aov(value~group,dpo)

summary(dpo_av)

dpo_tukey<- TukeyHSD(dpo_av)

dpo_tukey

plot(data6_tukey) # bu anlaşılmıyor çünkü değerleri yuvarlamıştım

plot(dpo_tukey) # bu anlaşılır

data6 <- [Link] (

signal=c(294.9, 287.6, 195.2, 290.3, 309.7, 201.2, 291.1, 322.7, 203.7, 325.7, 301.7, 205.5, 302.2, 310.1,
196.4, 303.8, 297.5, 211.8, 297.1, 298.2, 209.8,

287.9, 292.5, 201.3, 311.9, 312.2, 191.5, 294.8, 284.8, 195.9),

condition = factor(rep(c("ctrl","sirna1","sirna2"),10)))

data6 # to see the data

plot(data6_tukey)

[Link]::[Link](data6$signal,data6$condition)

data7 <- [Link]( response=c(6,9.7, 5.8,


6,8.8,6.5,5.7,8.5,5.9,5.6,9.2,6,5.9,8.5,5.6,5.9,9,6.1,6.3,9.1,5.9,6,9.3,5,6.5,9,6,5.7,9.3,6.3),

treatment=factor(rep(c("vehicle", "drug1","drug2"),10)))
> [Link](data6$signal)

> [Link](data7$response)

data7

#for non-normal use Kruskal-Wallis instead of Anova

[Link](response~treatment,data7)

#for non-normal use Dunn-Holland-Wolfe test for pairwise testing within group like Tukey after Anova,
Dunn after Kruskal

[Link]("[Link]")

[Link]::[Link](data7$response,data7$treatment)

-------------------

data600 <- [Link] (

signal=c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,

3, 3, 3, 3, 3, 3, 3, 3, 3),

condition = factor(rep(c("ctrlx","sirna1x","sirna2x"),10)))

data600 # to see the data

data600_av <- aov(signal ~ condition, data600)

summary(data600_av)

-----

TELLS US THERE IS A SIGNIFICANT DIFFERENCE THAT DEPENDS ON THE "condition" VARIABLE

Df Sum Sq Mean Sq F value Pr(>F)

condition 2 6.667 3.333 3.45e+31 <2e-16 ***

Residuals 27 0.000 0.000


Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

-----

plot(data600_tukey)

TESTS ALL THE PAIRWISE COMBINATIONS

data7 <-
[Link]( response=c(1826,1968,1961,5418,4711,3403,1394,1362,1856,2592,3200,3796,1102,906,1008,9
09,796,992,874,777,762,1130,1191,967,751,930,980,717,657,724,619,681,706,1718,1919,1371),
+ treatment=factor(rep(c("ccECM", "glass","TGF"),12)))
> View(data7)
> #for non-normal use Kruskal-Wallis instead of Anova
> [Link](response~treatment,data7)

library(readxl)
library(ggplot2)
library(cowplot)

df <- read_excel("C:/Users/fatih/OneDrive/Documents/[Link]",
sheet = "testforplot1")
df <- read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]",
sheet = "testforplot1")

("C:\\Users\\devrim-okvur\\Desktop\\[Link]")

base_plot <- ggplot(df, aes(x = 1, color = factor(replicate))) +


labs(x = "",
y = "",
color = "Legend") +
theme_bw() +
theme([Link].x = element_blank(),
[Link] = element_blank())

plot_area <- base_plot +


geom_point(aes(y =Area), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "Area") +
guides(color = FALSE)
plot_circ <- base_plot +
geom_point(aes(y = Circ.), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "Circ.") +
guides(color = FALSE)

plot_ar <- base_plot +


geom_point(aes(y = AR), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "AR") +
guides(color = FALSE)

plot_round <- base_plot +


geom_point(aes(y = Round), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "Round") +
guides(color = FALSE)

plot_solidity <- base_plot +


geom_point(aes(y = Solidity), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "Solidity")

combined_plot <- plot_grid(plot_area, plot_circ, plot_ar,


plot_round, plot_solidity, ncol = 5)

combined_plot

------------------------------------- -----------------------------------------
base_plot <- ggplot(my_data_long, aes(x = 1, color = factor(replicate))) +
labs(x = "",
y = "",
color = "Legend") +
theme_bw() +
theme([Link].x = element_blank(),
[Link] = element_blank())

plot_cond1 <- base_plot +


geom_point(aes(y =cond1), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "cond1") +
guides(color = FALSE)

plot_cond2 <- base_plot +


geom_point(aes(y =cond2), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "Cond2") +
guides(color = FALSE)

plot_cond3 <- base_plot +


geom_point(aes(y = cond3), position = position_jitterdodge([Link] = 1), size = 1) +
labs(y = "cond3") +
guides(color = FALSE)

combined_plot <- plot_grid(plot_cond1, plot_cond2, plot_cond3, ncol = 4)

combined_plot
# Install and load the tidyverse package if not already installed

if (!requireNamespace("tidyverse", quietly = TRUE)) {

[Link]("tidyverse")

# Load the tidyverse package

library(tidyverse)

library("readxl")

my_data <- read_excel("C:\\Users\\devrim-okvur\\Desktop\\[Link]")

# Assuming your data frame is named 'my_data'

# Replace 'my_data' with the actual name of your data frame

# Reshape the data from wide to long format

my_data_long <- my_data %>%

gather(key = "cond", value = "Measurements", -replicate)

# Sort the data based on Experimental Repeat Number and Condition

my_data_long <- my_data_long %>%

arrange(replicate, cond)

# Print the resulting data frame

print(my_data_long)

# Install and load the writexl package if not already installed

if (!requireNamespace("writexl", quietly = TRUE)) {

[Link]("writexl")

}
# Load the writexl package

library(writexl)

library(openxlsx)

# Specify the file path where you want to save the Excel file

excel_file_path <- "C:\\Users\\devrim-okvur\\Desktop\\my_data_long.xlsx"

# Write the data frame to an Excel file

write_xlsx(my_data_long, excel_file_path)

# Print a message indicating where the file has been saved

cat("Data has been exported to:", excel_file_path, "\n")

# Specify the file path where you want to save the CSV file

csv_file_path <- "path/to/your/folder/my_data_long.csv"

# Write the data frame to a CSV file

[Link](my_data_long, csv_file_path, [Link] = FALSE)

# Print a message indicating where the file has been saved

cat("Data has been exported to:", csv_file_path, "\n")

# Assuming your data frame is named 'my_data_long'

# Replace 'my_data_long' with the actual name of your data frame


# Install and load the ggplot2 package if not already installed

if (!requireNamespace("ggplot2", quietly = TRUE)) {

[Link]("ggplot2")

library(ggplot2)

# Scatter plot with ggplot2

ggplot(my_data_long, aes(x = replicate, y = Measurements, color = cond)) +

geom_point(position = position_jitter(width = 0.2, height = 0), alpha = 0.6, size = 2) +

geom_smooth(method = "lm", se = FALSE, color = "black") +

labs(title = "SuperPlotsofData", x = "replicate", y = "Measurements") +

theme_minimal() +

theme([Link]="right") +

scale_color_manual(values = c("blue", "green", "red")) # Customize colors based on your needs

xxxxxxxxxxxxxxxxx

# Assuming your data frame is named 'my_data_long'

# Replace 'my_data_long' with the actual name of your data frame

# Install and load the ggplot2 package if not already installed

if (!requireNamespace("ggplot2", quietly = TRUE)) {

[Link]("ggplot2")

library(ggplot2)

# Scatter plot with ggplot2

ggplot(my_data_long, aes(x = cond, y = Measurements, color = factor(replicate))) +

geom_point(position = position_jitter(width = 0.2, height = 0), alpha = 0.6, size = 2) +


geom_smooth(aes(group = factor(replicate)), method = "lm", se = FALSE, color = "black") +

labs(title = "SuperPlotsofData", x = "Condition", y = "Measurements") +

theme_minimal() +

theme([Link]="right") +

scale_color_manual(values = c("1" = "magenta", "2" = "green", "3" = "red")) # Customize colors based
on your needs
Absolutely! You can achieve similar visualizations in Python using the `matplotlib` and `seaborn`
libraries. Here's an example using `seaborn`:

```python

import seaborn as sns

import [Link] as plt

# Assuming your DataFrame is named 'my_data_long'

# Replace 'my_data_long' with the actual name of your DataFrame

# Scatter plot with seaborn

[Link](style="whitegrid")

[Link](figsize=(10, 6))

# Adjust the palette and markers based on your preferences

[Link](data=my_data_long, x="Condition", y="Measurements",


hue="Experimental_Repeat_Number",

palette={"1": "blue", "2": "green", "3": "red"},

marker='o', alpha=0.6, s=80)

# Add a linear regression line

[Link](data=my_data_long, x="Condition", y="Measurements", scatter=False, color='black')

# Set plot labels and title

[Link]("SuperPlotsofData")

[Link]("Condition")

[Link]("Measurements")

# Show the legend


[Link](title="Experimental Repeat Number")

# Show the plot

[Link]()

```

In this Python code:

- `seaborn` is used for creating the scatter plot and regression line.

- The `hue` parameter is used to differentiate replicates (Experimental Repeat Number) using different
colors.

- `regplot` is used to add a linear regression line.

- Adjust the palette (`palette`) and markers (`marker`) based on your preferences.

Make sure to install the necessary libraries by running `pip install seaborn matplotlib` if you haven't
already.

Feel free to customize the code based on your specific needs and preferences.

import seaborn as sns

import [Link] as plt

# Assuming your DataFrame is named 'my_data_long'

# Replace 'my_data_long' with the actual name of your DataFrame

# Scatter plot with seaborn

[Link](style="whitegrid")

[Link](figsize=(10, 6))

# Adjust the palette and markers based on your preferences


[Link](data=my_data_long, x="Condition", y="Measurements",
hue="Experimental_Repeat_Number",

palette={"1": "blue", "2": "green", "3": "red"},

marker='o', alpha=0.6, s=80)

# Add a linear regression line

[Link](data=my_data_long, x="Condition", y="Measurements", scatter=False, color='black')

# Set plot labels and title

[Link]("SuperPlotsofData")

[Link]("Condition")

[Link]("Measurements")

# Show the legend

[Link](title="Experimental Repeat Number")

# Show the plot

[Link]()

You might also like