Ask Your Question
2

How can we use a for/nested loop in r to generate a new column?

asked 2023-06-13 14:18:28 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-13 14:30:01 +0000

qstack gravatar image

Assuming we have a data frame df with existing columns, to generate a new column new_col using a for/nested loop in R, we can do the following:

# Create an empty vector to store the new column
new_col <- c()

# Loop through each row of the data frame
for (i in 1:nrow(df)) {

  # Create an empty variable to store the cumulative value
  cum_value <- 0

  # Loop through each column of the row
  for (j in 1:ncol(df)) {

    # Add the value of the current column to the cumulative value
    cum_value <- cum_value + df[i,j]

  }

  # Append the cumulative value to the new column vector
  new_col <- c(new_col, cum_value)

}

# Add the new column to the data frame
df$new_col <- new_col

In this example, we are generating a new column that contains the cumulative sum of all the values in each row of the data frame. We first create an empty vector new_col to store the new column. We then loop through each row of the data frame using a for loop, and for each row, we create an empty variable cum_value to store the cumulative value. We then loop through each column of the row using a nested for loop, and for each column, we add the value of the current column to the cumulative value. Once we have calculated the cumulative value for the row, we append it to the new_col vector. Finally, we add the new_col vector to the data frame as a new column using the $ operator.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-13 14:18:28 +0000

Seen: 13 times

Last updated: Jun 13 '23