Ask Your Question
4

What is the process to add up the rows of specified columns and then add them to a comparably structured dataset using rbind?

asked 2023-03-30 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-05-25 08:00:00 +0000

pufferfish gravatar image

Assuming you have two dataframes (df1 and df2) with the same column structure and you want to add up the values of columns 2 and 3 for each row in both dataframes and then combine the result in a new dataframe (df3) using rbind(), you can use the following code:

# create example dataframes
df1 <- data.frame(col1 = c("A", "B", "C"), col2 = c(1, 2, 3), col3 = c(4, 5, 6))
df2 <- data.frame(col1 = c("D", "E", "F"), col2 = c(7, 8, 9), col3 = c(10, 11, 12))

# sum columns 2 and 3 for each dataframe
df1_sums <- apply(df1[,2:3], 1, sum)
df2_sums <- apply(df2[,2:3], 1, sum)

# combine the sums in a new dataframe using rbind()
df3 <- rbind(df1_sums, df2_sums)

# add column names to the new dataframe
colnames(df3) <- c("col2_sum", "col3_sum")

In the above code, the apply() function is used to sum up the values of columns 2 and 3 for each row in both dataframes. The resulting sums are then combined in a new dataframe (df3) using rbind(). Finally, column names are added to the new dataframe using colnames().

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-03-30 11:00:00 +0000

Seen: 8 times

Last updated: May 25 '21