Home > Software engineering >  for-loop for R script based on the input file data
for-loop for R script based on the input file data

Time:10-20

The below R code works.

library(ggplot2)
d <- read.csv('./data.csv')
qplot(d$Time,d$Y)
ggsave(file='./test.png', dpi=300, w=4, h=3)

data.csv is as follows.

Time Y
1 2.4
2 3.0
3 4.4
4 5.0
5 8.4
6 9.0

##########################

If the data-all.csv would be like below, I want to make a figure for each person.

Time Y person
1 2.4 John
2 3.0 John
3 4.4 John
4 5.0 John
5 8.4 John
6 9.0 John
1 1.4 Nancy
2 2.0 Nancy
3 3.1 Nancy
4 3.9 Nancy
5 8.1 Nancy
6 8.8 Nancy
1 3.4 Bob
2 4.2 Bob
3 5.4 Bob
4 6.9 Bob
5 7.7 Bob
6 8.2 Bob

Of course, I can make the R code as below with the three divided data-all.csv, but I want to work the same procedure using for-loop or similar procedures in case I have a very large number of persons in the file.

The data-all.csv consists of only three persons, but I want to use the similar file consisting of more than 100 persons.

Similar questions might be published on the Web, but I am not so familiar with R and I could not make the R code I want.

I would appreciate it if you show me the code.

library(ggplot2)

d <- read.csv('./data-all_John.csv')
qplot(d$Time,d$Y)
ggsave(file='./test_John.png', dpi=300, w=4, h=3)

d <- read.csv('./data-all_Nancy.csv')
qplot(d$Time,d$Y)
ggsave(file='./test_Nancy.png', dpi=300, w=4, h=3)

d <- read.csv('./data-all_Bob.csv')
qplot(d$Time,d$Y)
ggsave(file='./test_Bob.png', dpi=300, w=4, h=3)

CodePudding user response:

Try:


library(ggplot2)


d <- read.csv('./data-all.csv')
for(pers_i in unique(d$person)){
  d_i <- d[d$person == pers_i, ]
  qplot(d_i$Time,d_i$Y)
  ggsave(file=paste0('./test_', pers_i, '.png'), dpi=300, w=4, h=3)
}
  • Related