Reputation: 433
I have a data table in R with 900 rows and 6 columns. For each row, I want to divide the value in column 4 by the number of rows and store the result in column 6. Currently I am using a for loop:
for (i in c(1:nrow(data))){
data[i,6] = data[i,4]/nrow(data)
}
How do I do this without the for loop?
Upvotes: 1
Views: 4304
Reputation: 7654
Or data <- transform(data, column6 = data$column4/nrow(data))
Or you could use dplyr
and its summarise
function.
Upvotes: 0
Reputation: 1055
Try this. You don't need to use a 'for loop'. If you use a 'for loop' it will take significant time to compute. But using following code it will calculate quickly.
data$column6<- (data$column4)/nrow(data)
Upvotes: 3