Reputation:
A representation of my sample is :
dat<-read.table(text=" AN1 AN2 AN3 ANM1 ANM2 ANM3
82 78 77 98 86 93
79 73 99 85 86 77
82 74 84 79 73 76
89 73 96 83 72 80
70 71 72 84 76 99
78 76 95 87 76 98
72 87 74 76 79 88
95 85 85 96 94 81
72 86 99 76 93 72
80 97 90 95 77 91
94 95 79 90 78 95
94 83 84 91 73 100
77 92 95 82 83 95
82 82 84 78 96 90
81 83 85 71 76 95
89 79 87 72 99 98
93 96 84 74 82 86
77 98 89 84 87 86
86 98 92 95 72 89
98 92 99 87 93 99",header=TRUE)
I want to make a correlation between AN1 and ANM1; AN2 and ANM2 and AN3 and ANM3 using a loop. I want to get "basic Plot" which is available here. So I will get three scatter plots separately.
I have used the following codes, but it does not work:
AN<- dat[1:3]; ANM<- dat[4:6];
lapply(1:3, function(x) ggscatter(AN=[,x],ANM[,x]))
Upvotes: 0
Views: 120
Reputation: 333
I think with a for
loop your code would look better. So, to purely reproduce your example, I would do something like this:
library(ggpubr)
dat<-read.table(text=" AN1 AN2 AN3 ANM1 ANM2 ANM3
82 78 77 98 86 93
79 73 99 85 86 77
82 74 84 79 73 76
89 73 96 83 72 80
70 71 72 84 76 99
78 76 95 87 76 98
72 87 74 76 79 88
95 85 85 96 94 81
72 86 99 76 93 72
80 97 90 95 77 91
94 95 79 90 78 95
94 83 84 91 73 100
77 92 95 82 83 95
82 82 84 78 96 90
81 83 85 71 76 95
89 79 87 72 99 98
93 96 84 74 82 86
77 98 89 84 87 86
86 98 92 95 72 89
98 92 99 87 93 99",header=TRUE)
for(i in 1:3){
AN <- paste0("AN", i)
ANM <- paste0("ANM", i)
print(
ggscatter(dat, x = AN, y = ANM)
)
}
To try to create something similar with the basic plots from the link provided, I would change the for
loop to something like:
for(i in 1:3){
AN <- paste0("AN", i)
ANM <- paste0("ANM", i)
print(
ggscatter(dat, x = AN, y = ANM,
add = "reg.line",
conf.int = TRUE,
add.params = list(color = "blue", fill = "lightgray")) +
stat_cor(method = "pearson", label.x = 3, label.y = 30) # Here label.x and label.y deform the plot, seems to be a case to tune them to your needs.
)
}
Now, if you must use lapply
I would try to create some abstraction by creating a function:
create_plot <- function(data, prefix_x, prefix_y, index) {
x_col <- paste0(prefix_x, index)
y_col <- paste0(prefix_y, index)
g <- ggscatter(data, x = x_col, y = y_col,
add = "reg.line",
conf.int = TRUE,
add.params = list(color = "blue", fill = "lightgray")) +
stat_cor(method = "pearson")
return(g)
}
lapply(1:3, create_plot, data = dat, prefix_x = "AN", prefix_y = "ANM")
Upvotes: 1