Error in FUN(X[[i]], ...) : object 'Total' not found

This is the code:
adde_percent <- lapply(added_total, function(x){
last_row <- nrow(x)
pct <- Total / sum(Total)
x[last_row+1,] <- c("percentage", pct)
x
})
I have a list of data frames and want to add the percentage at the end of each data frame in a list. I already added the total. This is a screenshot of a data frame:image

If I'm not mistaken, you added the word "Total" in the last row of your data frame. So it is not a separate variable.

Easiest way in your case to compute both the total and the percentage at the same time, and bind them on the last row at once.

Note that it is unusual in R to put a total in a row of a data frame: basically the total is metadata (in this context), and the cells of the data frame should only contain data. You end up with columns that contain a mix of data and metadata. Once you are in this situation, you can't really work with the data frame anymore. I would recommend to keep your full data frame without additional row, and separately compute the Totals and percentage, and only print them together in the final output.

The problem has solved. Now I want to move the percentage and total to the top of each data frame in the list. Do you know to do it? thank you.

The easiest is still to store them in separate data frames, then simply to rbind(totals, data) instead of rbind(data, totals).

For an existing data frame, I guess I would create a new one:

n <- nrow(old_df)
new_df <- rbind(old_df[c(n-1, n),], old_df[1:(n-2)])

Thank you @AlexisW for answering.
now I want to sort the columns horizontally largest-to-smallest by the second row in the list. Is it possible?

Well, everything is possible, doesn't mean it's a good idea: this is really not the standard use of a data frame. Anyway, you can simply use the base function order() to get the order, and apply it with slicing.

my_order <- order(my_df[2,])
reordered_df <- my_df[,my_order]

This topic was automatically closed 7 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.