user2916044 - 3 years ago 136
R Question

R-create a data frame with 2 rows in a loop

How can I create a data frame with 2 rows with this structure?

``````X1  Y1 Calc1  X2  Y2 Calc2 … Xn  Yn  Calcn
1   4  0.25   2   5  0.4     i   i+3 i/i+3
``````

I tried using this code:

``````dataRowTemp<-numeric(length = 0)
dataRow<-numeric(length = 0)

for (i in  1:150){
X<- i
Y<- i+3
Calc <- X/Y
dataRowTemp <- c(X,Y,Calc)
dataRow<-c(dataRow,dataRowTemp)
headerRowTemp <- paste(c("X", i),c("Y", i),c("Calc", i),sep='')
}
``````

unfortunately, I can’t create the a correct header (titleRow) and how can I combine them to data.frame later?

Is there an elegant and better way to do so?

Build a function to be used in each iteration.

``````myfun <- function(i) {
X <- i
Y <- i + 3
c(X = X, Y = Y, Calc = X/Y)
}
``````

Set the number of iterations.

``````n <- 150
``````

Apply the function to the numbers from 1 to n, use `matrix(..., nrow = 1)` to store the output in a matrix of only 1 row, and transform it into a `data.frame` (because it is what you say you aim at).

``````mydf <- data.frame(matrix(sapply(seq_len(n), myfun), nrow = 1))
``````

Use `paste0` in a loop to iteratively assign names to the column of your `data.frame`.

``````names(mydf) <- c(sapply(seq_len(n), function(i) paste0(c('X', 'Y', 'Calc'), i)))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download