Sss
Sss

Reputation: 447

Loop over a list in R

I want to do an operation if each data frame of a list. I want to perform the Kolmogorov–Smirnov (KS) test for one column in each data frame. I am using the code below but it is not working:

PDF_mean <- matrix(nrow = length(siteNumber), ncol = 4)
PDF_mean <- data.frame(PDF_mean)
names(PDF_mean) <- c("station","normal","gamma","gev")


listDF <- mget(ls(pattern="DSF_moments_"))
length(listDF)
i <- 1

for (i in length(listDF)) {

PDF_mean$station[i] <- siteNumber[i]
PDF_mean$normal[i] <- ks.test(list[i]$mean,"pnorm")$p.value
PDF_mean$gev[i] <- ks.test(list[i]$mean,"pgev")$p.value
PDF_mean$gamma[i] <- ks.test(list[i]$mean,"gamma")$p.value

}

Any help?

Upvotes: 0

Views: 55

Answers (1)

akrun
akrun

Reputation: 887881

It is not length(listDF) instead, it would be seq_along(listDF) or 1:length(listDF) (however, it is more appropriate with seq_along) because length is a single value and it is not doing any loop

for(i in seq_along(listDF)) {

  PDF_mean$station[i] <- listDF[[i]]$siteNumber
  PDF_mean$normal[i] <- ks.test(listDF[[i]]$mean,"pnorm")$p.value
  PDF_mean$gev[i] <- ks.test(listDF[[i]]$mean,"pgev")$p.value
  PDF_mean$gamma[i] <- ks.test(listDF[[i]]$mean,"gamma")$p.value
 }      

Upvotes: 2

Related Questions