将NA更改为""在整个data.frame中

时间:2017-04-11 21:36:42

标签: r dplyr

我想将所有NA更改为""在由字符串组成的data.frame中。我试图使用Dplyr包的mutate_each函数,但它不起作用(我得到数字代替字符串)。

Df_with_NA <- as.data.frame(rbind(c("toto", "titi", NA, NA), c("tata", "tztz", "tutu", NA), c("toto","titi", "tutu", "tyty")))

empty_as_na <- function(x){
  ifelse(is.na(x), "", x)
}

Df_with_empty_string_instead_of_NA <- Df_with_NA %>% mutate_each(funs(empty_as_na)) 

你能告诉我出了什么问题吗?

感谢

2 个答案:

答案 0 :(得分:2)

#First convert elements of 'Df_with_NA' to character and store in 'df'
#This step is necessary because you didn't use stringsAsFactors = FALSE
#when creating 'Df_with_NA'
df = sapply(Df_with_NA, as.character)

#Then replace NA with ""
df[is.na(df)] = ""
df
#     V1     V2     V3     V4    
#[1,] "toto" "titi" ""     ""    
#[2,] "tata" "tztz" "tutu" ""    
#[3,] "toto" "titi" "tutu" "tyty"

答案 1 :(得分:0)

使用简单的旧apply()你应该没问题。考虑一下:

Df_with_NA <- as.data.frame(rbind(c("toto", "titi", NA, NA), 
                                  c("tata", "tztz", "tutu", NA), 
                                  c("toto","titi", "tutu", "tyty")))
Df_with_NA
#     V1   V2   V3   V4
# 1 toto titi <NA> <NA>
# 2 tata tztz tutu <NA>
# 3 toto titi tutu tyty
empty_as_na <- function(x){
  ifelse(is.na(x), "", x)
}

apply(Df_with_NA, 2, empty_as_na)
#      V1     V2     V3     V4    
# [1,] "toto" "titi" ""     ""    
# [2,] "tata" "tztz" "tutu" ""    
# [3,] "toto" "titi" "tutu" "tyty"