如何基于DF1-DF4的NROW值创建含统计列的新DataFrame
Solution to Build Your Custom DataFrame in R
Hey there! Let's put together that DataFrame you need step by step. First, I'll clarify the values and fix the minor naming mix-up where you reused C for both Z's row count and DF3's row count.
Step 1: Define the Row Counts
First, let's assign the row counts you calculated to clear, non-conflicting variables:
# Row counts from your original DataFrames A_nrow <- 100 # NROW(DF1) B_nrow <- 80 # NROW(DF2) Z_nrow <- 30 # NROW(Z) (you initially labeled this as C) C_nrow <- 50 # NROW(DF3) D_nrow <- 25 # NROW(DF4)
Step 2: Construct the Custom DataFrame
We'll build the DataFrame using your specified calculation rules. For the Z row, I used the explicit values you provided (15 for Count and Count2) since the formula you mentioned (Count2-Nrow(Z)) would result in a negative number that doesn't align with your desired 15 value:
# Create the data frame with all required columns custom_df <- data.frame( DF = c("A", "B", "Z", "C", "D"), Count = c( A_nrow, B_nrow, 15, # Explicit value per your requirement C_nrow, D_nrow ), Count2 = c( 0, A_nrow - B_nrow, # A - B = 100 - 80 15, # Explicit value per your requirement B_nrow - C_nrow, # B - C = 80 - 50 C_nrow - D_nrow # C - D = 50 - 25 ), Percentage = c( 0, (A_nrow - B_nrow)/A_nrow * 100, # 20/100 = 20% 15/(A_nrow - B_nrow) * 100, # 15/20 = 75% (B_nrow - C_nrow)/B_nrow * 100, # 30/80 = 37.5% (C_nrow - D_nrow)/C_nrow * 100 # 25/50 = 50% ) ) # Format the Percentage column to show % sign custom_df$Percentage <- paste0(custom_df$Percentage, "%")
Step 3: View the Result
When you run the code above, you'll get exactly the DataFrame you need:
print(custom_df) # DF Count Count2 Percentage # 1 A 100 0 0% # 2 B 80 20 20% # 3 Z 15 15 75% # 4 C 50 30 37.5% # 5 D 25 25 50%
内容的提问来源于stack exchange,提问作者user9211845
相关产品推荐
相关产品推荐

