loop output saving

Hi every one
I would like to ask for some suggestions.
I created a cod as fallow. The output of the loop has 3 numbers which is correct. But when I make a data frame, then the out output has only one number.

D<- read.csv(file.choose(), header = TRUE)
head(D)
attach(D)
library(ggplot2)
library(cowplot)
slope <- function(x, y){
mean_x <- mean(x)
mean_y <- mean(y)
nom <- sum((x - mean_x)*(y-mean_y))
denom <- sum((x - mean_x)^2)
m <- nom / denom
return(m)
}
x <- D[, 1]
y<- D[, 2:4]
for (i in y) {
D_fractal <- 3-(slope(log(x), log(i)))
print(D_fractal)
}
df1 <- data.frame(soil = c(1:3) , d= c(D_fractal))
print (df1)
write.csv(df1, file = "Y:/project2020/Data/texture/Texrure_modelling/d_m.csv", row.names = F)

111

Welcome! I'm afraid you'll need to supply some more info in order for helpers to be able to understand your problem (this is pretty common — when you're new to this stuff, it's hard to know how much information is enough!).

We can't observe D, which would be helpful in answering your question. The best thing would be if you can make your question into a reproducible example (follow the link for instructions and explanations). To include your data, you'll want to follow one of the methods discussed here.

If you try all that and get stuck, here's a fallback option...
  1. Edit your post and add in some of the code you have tried. It's OK it doesn't work! It's really helpful to see what you've been attempting. Be sure to format your code as code (it's hard to read unformatted code, and it can get garbled by the forum software)
  2. Include sample data:
    • If your data set is OK to share, run the following line and paste the output into your post. Again, be sure to format it as code :sparkles:
    dput(head(your_dataframe_name, 10))
    
    • If your data set can't be shared, run this line instead and paste the output into your post (and yes, format as code!) This will still share some information about your data. If it's truly confidential, I'm afraid you'll need to make a fake sample dataset to share.
    str(your_dataframe_name)
    

but I don't think we need to, to answer this.


I'm also not sure you're applying slope quite right. Note in the loop, the second arguement is log(i), which appears to call a single number in each loop (though, admittedly this is hard to tell without knowing D). However, slope needs a set of values for y to be calculated.

Completely agree with everything EconomiCurtis said, but I had a closer look anyway. And, just to stress the point, I am guessing here, because I don't know what your environment actually looks like.

...but it looks to me like maybe this it what you're going for...

slope <- function(x, y){
  x <- scale(log(x), scale = F)
  y <- scale(log(y), scale = F)
  sum(x * y) / sum(x^2)
}

D_fractal <- sapply(D[-1], function(y) 3 - slope(D$x, y))

thank you very much for your commend