Prafulla
Prafulla

Reputation: 585

Column name changes in R for loop for defined data frame

I have defined a blank data frame with the column name for calculation. When I use the data frame in for loop to bind the rows in data frame the column name gets change. How can I retain the column name intact.

I am using the below code.

res <- data.frame(Calculations = integer())
for (i in 1:3) {
  calc <- i * runif(1)
  res <- rbind(res, calc)
}
print(res)

Result I get from this code is

print(res)
  X0.890447217039764
1          0.8904472
2          1.9034397
3          1.8227991 

Whereas I am expecting

print(res)
  Calculations
1          0.8904472
2          1.9034397
3          1.8227991

Upvotes: 1

Views: 62

Answers (3)

zx8754
zx8754

Reputation: 56169

We can predefine number of rows for the blank data.frame, then assign each row using a forloop:

res <- data.frame(Calculations = integer(length = 3))

for (i in 1:3) {
  res[i , "Calculations"] <- i * runif(1)
}

Note:

  • defining as integer, then assigning floating points, maybe use numeric(length = 3) instead
  • I assume your real calculations are more complex than this, otherwise there are better R way of doing things, for example @Ronak's answer.
  • Growing objects in a forloop is not advised. res <- rbind(res, calc)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

Do you really need to add values to a column in a loop ?

If you are creating a new dataframe you can do

data.frame(Calculations = runif(3))

Or if the dataframe is already existing, you can add a new column to it by doing

df$Calculations <- runif(3)

Upvotes: 2

user10307643
user10307643

Reputation:

for (i in 1:3) {
  calc <- i * runif(1)
  res <- rbind(res, list(Calculations=calc))
}

Another possibility is to rename after the loop:

colnames(res) <- "Calculations"

Upvotes: 1

Related Questions