Help with simple for loop

So I'm new to R, and I am trying to make a simple for loop to find the average of the row 'kJ/mol' for rows 1 and 2, 2 and 3, 3 and 4, and so on. I have the answer already through excel, but am trying to replicate through R. I have some broken code kind of on the right track but not sure where to go from here. Any advice would be helpful. Code below.

data <- data.frame(assign2)

for i >= 1, data
i <- ('kJ/mol')
average <- ((i +(i+1))/2)

Error message:

for i >= 1, data
Error: unexpected symbol in "for i"
i <- ('kJ/mol')
average <- ((i +(i+1))/2)
Error in i + 1 : non-numeric argument to binary operator
Error in print(average) : object 'average' not found

In R, we'd refer to kJ/mol in your table as a column or variable.
Without a for loop, you can quickly get the mean of a column with


$ is a shorthand for extracting named elements of a list. More details at$%20#subsetting-1

With the tidyverse, you might approach a problem like this with

data %>%
    mean = mean(`kJ/mol`)

Since this is an course assignment, I'm not going to directly answer your question, but I will point out that for loops in R work similarly, but differently to the code you set up. Here's some details on how to get started.

Also, it's helpful and tidy to format your code into code chunks when interacting with folks on forums like this.. Details on how to do that here: FAQ: How to format your code

People also like to see coding questions like this in the form of reproducible examples (reprex for short). Details on how to create those here, FAQ: What's a reproducible example (`reprex`) and how do I do one?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.