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.r312 chars17 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