本文介绍了设置< NA>空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有NA行的数据框:
I have a dataframe with an NA row:
df = data.frame(c("classA", NA, "classB"), t(data.frame(rep("A", 5), rep(NA, 5), rep("B", 5))))
rownames(df) <- c(1,2,3)
colnames(df) <- c("class", paste("Year", 1:5, sep = ""))
> df
class Year1 Year2 Year3 Year4 Year5
1 classA A A A A A
2 <NA> <NA> <NA> <NA> <NA> <NA>
3 classB B B B B B
我故意介绍了空行(NA行),因为我想在classA行和classB行之间留一些空间.
I introduced the empty row (NA row) on purpose because I wanted to have some space between classA row and classB row.
现在,我想用空白替换<NA>
,以便第二行看起来像一个空行.
Now, I would like to substitute the <NA>
by blank, so that the second row looks like an empty row.
我尝试过:
df[is.na(df)] <- ""
和
df[df == "NA"] <- ""
但是没用.
有什么想法吗?谢谢!
推荐答案
另一种选择:
df <- sapply(df, as.character) # since your values are `factor`
df[is.na(df)] <- 0
如果要空白而不是零
> 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"
如果需要data.frame,则只需使用as.data.drame
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
这篇关于设置< NA>空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!