R-tidyr-spread()-将NA作为列名处理 [英] R - tidyr - spread() - dealing with NA as column name
问题描述
我正在使用tidyr::spread()
将多个类别变量分布到布尔列.由于数据包含NA,因此spread
会创建一个没有名称的新列.
I am spreading multiple categorical variables to Boolean columns using tidyr::spread()
. As the data contains NAs, spread
creates a new column without a name.
我正在寻找一种摆脱使用NA的方法
What I'm looking for is a way to get rid off the NAs using
a)管道解决方案(我尝试过select_()
和'['()
,但不知道如何引用NA列的名称或索引)或
a) a piping solution (I've tried select_()
and '['()
, but don't know how to refer to the NA column's name or index) or
b)一个自定义函数,效果会更好
b) a custom function, which would be even better
c)如果可能的话,一种简单地不生成NA列的方式,与Hadleyverse兼容.
c) a way to simply not generate the NA columns, Hadleyverse compatible, if possible.
以下是我当前(且非常不重复)的解决方案.
Below is my current (and very inelegantly repetitive) solution.
library(tidyr)
library(dplyr)
test <- data.frame(id = 1:4, name = c("anna", "bert", "charles", "daniel"),
flower = as.factor(c("rose", "rose", NA, "petunia")),
music = as.factor(c("pop","classical", "rock", NA)),
degree = as.factor(c(NA, "PhD", "MSc", "MSc")))
test <- test %>%
mutate(truval = TRUE) %>%
spread(key = flower, value = truval, fill = FALSE)
test[ncol(test)] <- NULL
test <- test %>%
mutate(truval = TRUE) %>%
spread(key = music, value = truval, fill = FALSE)
test[ncol(test)] <- NULL
test <- test %>%
mutate(truval = TRUE) %>%
spread(key = degree, value = truval, fill = FALSE)
test[ncol(test)] <- NULL
test
推荐答案
我们可以在select
和backquotes
.
test %>%
mutate(truval= TRUE) %>%
spread(flower, truval, fill=FALSE) %>%
select(-`NA`)
# id name music degree petunia rose
#1 1 anna pop <NA> FALSE TRUE
#2 2 bert classical PhD FALSE TRUE
#3 3 charles rock MSc FALSE FALSE
#4 4 daniel <NA> MSc TRUE FALSE
我想很难不生成NA列,因为其他列中的观察结果与此相关.我们可以将filter
与is.na
一起使用,以删除花"列中具有"NA"的行,但是那样我们将丢失一行.第三行.
I guess it is difficult to not generate the NA column as the observations in other columns are tied to it. We could use filter
with is.na
to remove the row that has 'NA' in the 'flower' column, but then we will lose one row ie. the 3rd row.
这篇关于R-tidyr-spread()-将NA作为列名处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!