替換NULL我有以下數據框:在數據幀
freq.a freq.b
1 NULL 0.055
2 0.030 0.055
3 0.060 0.161
4 0.303 0.111
5 0.393 0.111
6 0.121 0.388
7 0.090 0.111
而且我想用一個實際的0。但是執行df.m[is.null(df.m)] <- 0
不改變數據幀的任何更換NULL
。如下
MWE(遺憾的長度):
library(plyr)
df.a <- c(5, 4, 5, 7, 3, 5, 6, 5, 5, 4, 5, 5, 4, 5, 4, 7, 2, 4, 4, 5, 3, 6, 5, 6, 4, 4, 5, 4, 5, 5, 6, 7, 4)
df.b <- c(1, 3, 4, 6, 2, 7, 7, 4, 3, 6, 6, 3, 6, 6, 5, 6, 6, 5)
df.a.count <- count(df.a)
df.b.count <- count(df.b)
#normalize the data
df.a.count$freq <- lapply(df.a.count$freq, function(X) X/length(df.a))
df.b.count$freq <- lapply(df.b.count$freq, function(X) X/length(df.b))
df.m <- merge(df.a.count, df.b.count, by ='x', all=TRUE)[2:3]
names(df.m) <- c('freq.a', 'freq.b')
#replace the NULL's with 0
df.m[is.null(df.m)] <- 0
如果你看'str(df.m)',每一列都是一個'list'。 'lapply'返回一個'list',這就是原因。 – akrun
嘗試'應用(df.m,2,函數(y)sapply(y,函數(x)ifelse(is.null(x),0,x)))'' – count