Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I recently started programming in R, and am trying to compute slopes for a data set. This is my code:

slopes<- vector()
gdd.values <- length(unique(data.gdd$GDD))
for (i in 1:gdd.values){
  subset.data <- data.gdd[which(data.gdd$GDD==i),]
  volume <- apply(subset.data[,4,6],1,prod)
  species.richness <- apply(subset.data[,7:59],1,sum)
  slopes[i] <- lm(log(species.richness) ~ log(volume))$coefficients[2]
}

When I run it the "slopes" value remains empty. All other values are fine (no other empty sets). Let me know if you find any obvious mistakes. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

Currently, you are iterating across the length of unique values and not unique values themselves. So, as @RobJensen comments, adjust the for loop vector and iteration. Hence, why some or all returned values result in missing as subset.data may contain no rows due to imprecise filter.

However, consider a more streamlined approach using the often underused and overlooked by() to subset dataset by needed grouping factor(s) and bind returned list into a vector:

coeff_list <- by(data.gdd, data.gdd$GDD, FUN=function(df) {
  volume <- apply(df[,4,6],1,prod)
  species.richness <- apply(df[,7:59],1,sum)
  lm(log(species.richness) ~ log(volume))$coefficients[2]
})

slopes <- do.call(c, coeff_list)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...