This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Getting error in for loop in R

Hi,

I am just trying to make multiple boxplots a time and using the following codes

`

files <- list.files(path="/datastore/VizLabbioData/godplz/merge_data/New folder/", pattern="*_merge.csv", full.names=TRUE, recursive=FALSE)
for( i in 1:files){
    NDVI_ts <- read.table(i, header = TRUE)
NDVI_ts
library(ggplot2)
library(scales)
library(tidyverse)
library(ggpubr)
NormalvsCancer<-interaction(NDVI_ts$Data, sep="\t")

        ######Outfile name as input file
filenm <- sub("csv", "pdf", files[i])
pdf(file=paste(filenm, "boxplot.pdf", sep=""))
      ##########
xlabs <- paste(levels(NDVI_ts$Data),"\n(N=",table(NDVI_ts$Data),")",sep="")
#ggplot(df,aes(x=group,y=x,color=group))+geom_boxplot()+scale_x_discrete(labels=xlabs)
p <- ggplot(data=NDVI_ts, aes(x=NormalvsCancer, y=log2_of_read_count)) + 
  geom_boxplot(aes(fill = Data), width = 0.6) + 
 scale_x_discrete(labels=xlabs) +
 geom_jitter(position=position_jitter(0.1)) +
 theme_bw() + theme(axis.text.x = element_text(angle = 360, hjust = 1)) 
                  #stat_compare_means(aes(group = Data), label = "p.format")
 print(p)
 dev.off()
}`

But I am getting an error like this Error in 1:files : NA/NaN argument In addition: Warning messages: 1: In 1:files : numerical expression has 2 elements: only the first used 2: In 1:files : NAs introduced by coercion

Any help is much appreciated. Thanks

r

try: for (i in files) instead of 1:files

Thanks, it removed the error what I was getting but giving no out file. There is no error. Any other suggestions

Look at @SMK's comment. You're mixing i and files[i]. In addition you're loading the libraries inside the for loop

Saw you using files[i], perhaps try changing for( i in 1:files){ to for (i in 1:length(files)) { and NDVI_ts <- read.table(i, header = TRUE) to NDVI_ts <- read.table(files[i], header = TRUE).

1 answer

Thank you all. You guys made my day.... Yahoo..

Solution for my problem is

for( i in 1:length(files)){
NDVI_ts <- read.table(files[i], header = TRUE)

I changed this only and its done.

Log in to answer this question.