You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:将data.frame列合并为4列,不足4个有效值保留NA

Solution for Reshaping Data Frame Rows by Removing NAs and Keeping 4 Columns

Here's a straightforward base R approach to get your desired result. We'll process each row individually to extract non-NA values, pad with NA to ensure exactly 4 elements, then combine everything back into a structured data frame.

Step-by-Step Code

# Your original data frame
df <- data.frame(
  'a' = c(1,4,NA,3), 
  'b' = c(3,NA,3,NA), 
  'c' = c(NA,2,NA,NA), 
  'd' = c(4,2,NA,NA), 
  'e'= c(NA,5,3,NA), 
  'f'= c(1,NA,NA,4), 
  'g'= c(NA,NA,NA,4)
)

# Process each row to extract non-NA values and pad to 4 elements
processed_rows <- apply(df, 1, function(row) {
  # Grab non-NA values in the original column order
  non_na_vals <- na.omit(row)
  # Pad with NA to ensure exactly 4 elements (truncate to first 4 if there are more)
  c(non_na_vals, rep(NA, 4))[1:4]
})

# Convert to data frame and rename columns to match your desired output
df.desired <- as.data.frame(t(processed_rows))
colnames(df.desired) <- c("a", "b", "c", "d")

# View the final result
df.desired

Output

a b  c  d
1 1 3  4  1
2 4 2  2  5
3 3 3 NA NA
4 3 4  4 NA

This method preserves the order of non-NA values as they appear in your original columns, and correctly fills in NA for any positions where a row has fewer than 4 valid values. If you ever encounter rows with more than 4 non-NA entries, this code will keep the first 4 (adjust the logic if you need a different behavior for that edge case).

内容的提问来源于stack exchange,提问作者Neal Barsch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:30:41