Loop to export rows as new dataframes whose names are i growing, then building pie charts

Hello everyone, I'm quite new to R coding and I'm trying to using a loop in order to obtain different dataframes on which creating different pie charts.
The dataset is the following, in table format:

pca=c(96.2,0.0,3.8)
pcr=c(3.1,92.8,4.1)
pls=c(3.0,0.3,96.7)
res=cbind(pca,pcr,pls)
colnames(res)<-c("PCA","PCR","PLS")
rownames(res)<-c("PCA","PCR","PLS")
res=as.table(res)
res

I'd like to obtain dataframes for all the columns to be named as follows res_1, 'res_2', 'res_3',
as follows for res_1, for instance:

res_1<-res[1,]
res_1<-as.data.frame(res_1)
res_1

I tried to use the following loop:

for(i in 1:dim(res)[1]){
  res_[i] <- res[i,]
}

but I keep on getting the following error:
1: In res_[i] <- res[i, ] : number of items to replace is not a multiple of replacement length and not the dataframes I'd need.
On the collected dataframes, I'd like to build the combined pie chart, as follows:

p_1<-plot_ly(res_1, labels = colnames(res), values = ~res_1, type = 'pie')
p_2<-plot_ly(res_2, labels = colnames(res), values = ~res_2, type = 'pie')
p_3<-plot_ly(res_3, labels = colnames(res), values = ~res_3, type = 'pie')
sublopt(p_1,p_2,p_3)

If possible, I'd like to convert the last step in a loop, since I could have to deal with higher number of columns in the original res, in order to build iteratively res_4, res_5, ... res_i, as well as p_4, p_5, etc.. to be subplotted at the end.
I think my question is quite silly, thank you in advance for the help!

Not a fan of the loop approach but you can achieve what you want by using the assign() function, something like this:

library(plotly)

pca=c(96.2,0.0,3.8)
pcr=c(3.1,92.8,4.1)
pls=c(3.0,0.3,96.7)
res=cbind(pca,pcr,pls)
colnames(res)<-c("PCA","PCR","PLS")
rownames(res)<-c("PCA","PCR","PLS")
res=as.table(res)
res

for(i in 1:dim(res)[1]){
  assign(paste0("p_",i), plot_ly(as.data.frame(res[i,]), labels = colnames(res), values = ~res[i,], type = 'pie'))
}
subplot(p_1,p_2,p_3)
1 Like

Dear @andresrcs, thank you very much for the quick reply.
I tried to run the code, but it seems that p_1, p_2 and p_3 are the same image, while I'd like to write 3 different pie charts, for the column PCA, PCR and PLS of the table res.
Thanks for you help

This solves that issue

for(i in 1:dim(res)[1]){
  assign(paste0("p_",i), plot_ly(as.data.frame(res[,i], nm = "y"), labels = colnames(res), values = ~y, type = 'pie'))
}

Although it seems like you can't use subplot() with pie charts, you have to use add_pie() and add them one by one.

1 Like

Thank you very much, it solved the problem! I'll try to focus on the eventual combination of the pie charts in an iterative way or I'll open a new thread,
Thank you very much again!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.