Getting error in for loop in R
1
0
Entering edit mode
4.8 years ago

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 • 1.3k views
ADD COMMENT
1
Entering edit mode

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).

ADD REPLY
0
Entering edit mode

Thanks dear. you made my day...!!

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
1
Entering edit mode

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

ADD REPLY
0
Entering edit mode
4.8 years ago

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.

ADD COMMENT

Login before adding your answer.

Traffic: 2652 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6