R 为值指定其列名
我在与dplyr合作,我有一个像这样的TIBLE:R 为值指定其列名,r,dplyr,R,Dplyr,我在与dplyr合作,我有一个像这样的TIBLE: df<- data_frame(one= c(1, NA, 1), two= c(NA,NA,1), three= c(1, 1,1) ) ---------------------------- # A tibble: 3 x 3 one two three <dbl> <dbl> <dbl> 1 1 NA
df<- data_frame(one= c(1, NA, 1),
two= c(NA,NA,1),
three= c(1, 1,1)
)
----------------------------
# A tibble: 3 x 3
one two three
<dbl> <dbl> <dbl>
1 1 NA 1
2 NA NA 1
3 1 1 1
----------------------------
----------------------------
# A tibble: 3 x 3
one two three
<dbl> <dbl> <dbl>
1 one NA three
2 NA NA three
3 one two three
----------------------------
但在我的真实df中,我有很多列,所以这个wat效率很低。
我需要一些更优雅的东西,使用mutate_at和列名,但这似乎很难。
我尝试了很多方法,但每次我都会出错。
有什么建议吗?如果数据集中只有1和NAs,将
col(df)
与数据集相乘,unlist
并根据索引,将其替换为数据集的names
,然后将其分配回原始数据
df[] <- names(df)[unlist(col(df)*df)]
df
# A tibble: 3 x 3
# one two three
# <chr> <chr> <chr>
#1 one <NA> three
#2 <NA> <NA> three
#3 one two three
非常感谢。太完美了。在dplyr模式下,您可以显式显示所使用的函数参数吗?(.y=,.f=,…)@andriatz
map2_df
采用两个参数.x
,.y
这里的.y
是我首先指定为名称(.)
的参数,即数据集的名称
df[] <- names(df)[unlist(col(df)*df)]
df
# A tibble: 3 x 3
# one two three
# <chr> <chr> <chr>
#1 one <NA> three
#2 <NA> <NA> three
#3 one two three
library(tidyverse)
df %>%
map2_df(names(.), ~replace(., !is.na(.), .y))
# A tibble: 3 x 3
# one two three
# <chr> <chr> <chr>
#1 one <NA> three
#2 <NA> <NA> three
#3 one two three