Setting <NA> to blank

╄→гoц情女王★ 提交于 2019-11-28 07:24:26

Another alternative:

df <- sapply(df, as.character) # since your values are `factor`
df[is.na(df)] <- 0

If you want blanks instead of zeroes

> df <- sapply(df, as.character)
> df[is.na(df)] <- " "
> df
     class    Year1 Year2 Year3 Year4 Year5
[1,] "classA" "A"   "A"   "A"   "A"   "A"  
[2,] " "      " "   " "   " "   " "   " "  
[3,] "classB" "B"   "B"   "B"   "B"   "B"  

If you want a data.frame, then just use as.data.drame

> as.data.frame(df)
   class Year1 Year2 Year3 Year4 Year5
1 classA     A     A     A     A     A
2                                     
3 classB     B     B     B     B     B

This answer is more of an extended comment.

What you're trying to do isn't what I would consider good practice. R is not, say, Excel, so doing something like this just to create visual separation in your data is just going to give you a headache later on down the line.

If you really only cared about the visual output, I can offer two suggestions:

  1. Use the na.print argument to print when you want to view the data with that visual separation.

    print(df, na.print = "")
    #    class Year1 Year2 Year3 Year4 Year5
    # 1 classA     A     A     A     A     A
    # 2                                     
    # 3 classB     B     B     B     B     B
    
  2. Realize that even the above is not the best suggestion. Get both visual and content separation by converting your data.frame to a list:

    split(df, df$class)
    # $classA
    #    class Year1 Year2 Year3 Year4 Year5
    # 1 classA     A     A     A     A     A
    # 
    # $classB
    #    class Year1 Year2 Year3 Year4 Year5
    # 3 classB     B     B     B     B     B
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!