0
c <- 3  # set the initial numbers
d <- acadfull[,c]
i <- 1
p <- 1
data <- data.frame()

while (i < 123 ) {     #loop

  ANS <- lm(caco ~ d, data=acadfull)

  data[p,1] <-  ANS$coefficients                             

  c <- c+1  
  i <- i+1
  p <- p+1
  d <- acadfull[,c]

  if (i==123)
    break

}

write.csv(c(snp,pos,data),"reg_results", row.names=F)

Any help would really be appreciated! When I run the above script, I get an error message saying

Error in `[<-.data.frame`(`*tmp*`, p, 1, value = c(1.48484848484849,      -0.0104895104895094,  : 
  replacement has 6 rows, data has 1

I get the error when this line is run

 ANS <- lm(caco ~ d, data=acadfull)
user227710
  • 3,164
  • 18
  • 35

2 Answers2

2

You can't subset a data frame like that, as you are telling the dataframe to change places that don't exist:

x <- data.frame()
x[ ,1]<-c(1, 2, 3)

Will give you the same error.

You can fix this in a variety of ways.

The easiest (and most inefficient) is using rbind:

data <-  rbind(data, ANS$coefficients)

As long are you aren't running a lot of data, this will be fine.

For a discussion of faster and more efficient ways of doing this, read this previous question - Growing a data.frame in a memory efficient manner

Community
  • 1
  • 1
jeremycg
  • 24,657
  • 5
  • 63
  • 74
0

I tried to simplify your code. You don't need the d and p variables. You can use rbind to add rows to your data frame and I adjusted the linear model.

As I don't know exactly what acadfull is, I couldn't test the code, but hopefully it will work.

c <- 3  # set the initial numbers
i <- 1

data <- data.frame()

while (i < 123 ) {     #loop

  ANS <- lm(acadfull$caco ~ acadfull[c])

  data <-  rbind(data, ANS$coefficients)

  c <- c+1  
  i <- i+1

  if (i==123)
    break    
}

write.csv(c(snp,pos,data),"reg_results", row.names=F)

You could even discard your i variable by changing your if statement:

if (c == 126)
  break
Paulo MiraMor
  • 1,582
  • 12
  • 30