如何在R语言中过滤数据框后动态新增列并合并数据?
Solution for Merging Tibble B into Subset of A (b == TRUE)
Got it, let's fix this right up. Your goal is to append all columns from B to A, filling NA for rows where b is FALSE—without explicitly naming B's columns. Your initial attempt failed because you were trying to assign a mismatched column count (you added an extra logical column with cbind(A$b==T,B)) to A's subset, which doesn't play nice with tibble's structure.
Here are clean one-liners for both dplyr and base R:
dplyr Approach
library(dplyr) A %>% bind_cols(B[ifelse(.$b, seq(nrow(B)), NA), ])
How it works:
ifelse(.$b, seq(nrow(B)), NA)generates a vector where we keep the row index of B for rows where A'sbis TRUE, and NA otherwise.- Indexing B with this vector returns a tibble where non-matching rows are filled with NA.
bind_colsattaches this modified B directly to A, preserving all column names from B automatically—no need to hardcode them.
Base R Approach
cbind(A, lapply(B, function(col) ifelse(A$b, col, NA)))
How it works:
lapply(B, function(col) ...)iterates over every column in B, creating a new vector where we take the column's value if A'sbis TRUE, else NA.cbindcombines these new vectors as columns to the original A data frame/tibble. Again, we never reference B's column names explicitly.
Note: Both methods assume that the number of rows in B matches the number of rows in A where b is TRUE (which is implied by your use case).
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

