create a loop in specific columns from a dataframe in r

To loop through specific columns in a dataframe in R, you can use a for loop in combination with the column index or name. Here's an example using column names:

main.r
# create example dataframe
df <- data.frame(
  x = c(1, 2, 3),
  y = c(4, 5, 6),
  z = c(7, 8, 9)
)
# create empty vector to store results
results <- numeric()

# loop through specific columns
for (col in c("x", "z")) {
  col_sum <- sum(df[[col]])
  results <- c(results, col_sum)
}

results  # prints [1] 11 18
312 chars
17 lines

In this example, we create a dataframe with three columns (x, y, and z). We then create an empty vector (results) to store the results of our loop. Using for(col in c("x", "z")), we loop through the specified columns (x and z), sum their values using sum(df[[col]]), and append the results to the results vector using results <- c(results, col_sum).

You can modify this example to suit your specific needs, such as changing the operation inside the loop or using column indices instead of names.

gistlibby LogSnag