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

如何使用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 (._x represents the current value)
    • If the value is 1, it replaces it with the column's name (from cur_column())
    • If the value is NA, it keeps it as-is
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:25:00