如何使用dplyr的transmute_all将含NA/1的列中1替换为列名?
Solution Using dplyr::transmute_all
Here's a straightforward way to get the result you want using dplyr's transmute_all function:
First, make sure you've loaded the dplyr package. Then we'll use cur_column() (a handy dplyr helper that returns the name of the current column being processed) to replace every 1 with its column name, while leaving NA values untouched.
library(dplyr) # Your sample input data df <- tibble( a = c(NA, 1, NA, 1, 1), b = c(1, NA, 1, 1, NA) ) # Perform the transformation transformed_df <- df %>% transmute_all(~ifelse(.x == 1, cur_column(), .x)) # View the final output transformed_df
Breakdown of the code:
transmute_all()applies the given function to every column in your data frame, preserving the original column names.- The lambda function
~ifelse(.x == 1, cur_column(), .x)does all the work:- It checks each value in the column (
._xrepresents the current value) - If the value is
1, it replaces it with the column's name (fromcur_column()) - If the value is
NA, it keeps it as-is
- It checks each value in the column (
- The resulting tibble will have character-type columns (since we're mixing character strings and
NAs), which matches your desired output.
When you run this code, you'll get exactly what you're looking for:
# A tibble: 5 × 2 a b <chr> <chr> 1 NA b 2 a NA 3 NA b 4 a b 5 a NA
内容的提问来源于stack exchange,提问作者justin cress
相关产品推荐
相关产品推荐

