user1971455
user1971455

Reputation: 433

R data frame, for every row, how to divide value in specified column by n and store in another column?

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

Answers (3)

lawyeR
lawyeR

Reputation: 7654

Or data <- transform(data, column6 = data$column4/nrow(data))

Or you could use dplyr and its summarise function.

Upvotes: 0

Manura Omal
Manura Omal

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

Matthew Lundberg
Matthew Lundberg

Reputation: 42649

data[,6] = data[,4]/nrow(data)

Upvotes: 2

Related Questions