Reputation: 585
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
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:
numeric(length = 3)
insteadres <- rbind(res, calc)
Upvotes: 1
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
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