请求协助:在data.frame中重复指定变量行并填充缺失值
Solution for Repeating Columns and Filling Missing Values in R
Hey there! Let's work through your data wrangling task together. I'll walk you through two common approaches—using the tidyverse suite and base R—to get your desired output.
First, let's define a sample version of your input data to make this concrete:
# Sample input data frame original_df <- data.frame( var1 = c("A", "B", "C"), var2 = c(10, 20, 30), var3 = c(NA, 5, NA) )
Approach 1: Using Tidyverse (dplyr + tidyr)
This method is intuitive and produces clean, readable code. We'll first fill missing var3 values with 0, then repeat each row 3 times (which keeps var3 tied to its original row while duplicating var1 and var2):
library(dplyr) library(tidyr) # Process the data target_df <- original_df %>% # Replace NA in var3 with 0 (coalesce is a cleaner alternative to ifelse here) mutate(var3 = coalesce(var3, 0)) %>% # Repeat each row 3 times uncount(3) # View the result target_df
Approach 2: Using Base R
If you prefer not to load external packages, this base R method achieves the same result:
# Step 1: Fill NA in var3 with 0 original_df$var3[is.na(original_df$var3)] <- 0 # Step 2: Repeat var1/var2 3 times per row, and match with var3 target_df <- data.frame( var1 = rep(original_df$var1, each = 3), var2 = rep(original_df$var2, each = 3), var3 = rep(original_df$var3, each = 3) ) # View the result target_df
Expected Output
Both methods will produce this final data frame:
var1 var2 var3 1 A 10 0 2 A 10 0 3 A 10 0 4 B 20 5 5 B 20 5 6 B 20 5 7 C 30 0 8 C 30 0 9 C 30 0
内容的提问来源于stack exchange,提问作者chermen
相关产品推荐
相关产品推荐

