MLn*_*wby 5 r function dataframe na
我在 Stackoverflow 上查看了多个答案,但仍然无法解决我的问题。我做了一个可以工作的功能,但是我添加了一些东西,现在它不再工作了。我想将所有 NA 替换为 0,这对我来说似乎很简单。
这是我的功能,我添加了bframe[is.na(bframe)] <- 0:
B <- function(frame1, frame2, column){
bframe <- merge(frame 1, frame2, by = column, all = TRUE)
bframe$result <- bframe$freq.x - bframe$freq.y
bframe$percentage <- (bframe$result/bframe$freq.y)*100
bframe[is.na(bframe)] <- 0
return(bframe)
}
B(DT2_1, 2_1, "BurgS")
Run Code Online (Sandbox Code Playgroud)
但是,它给出了这个错误:Error in '[<-.data.frame'('* tmp *, thisvar, value = 0) : duplicate subscripts for columns。
出现错误是因为存在 NA 并且无法执行计算:
BurgS freq.x freq.y result percentage percentageABS
1 9204 184042 -174838 -94.99897 94.99897
2 150 3034 -2884 -95.05603 95.05603
3 130 2602 -2472 -95.00384 95.00384
98 NA 47 NA NA NA
Run Code Online (Sandbox Code Playgroud)
并非每个数据帧都具有这种结构,因此我正在寻找一种可以更改整个数据集中的 NA 的解决方案。有人可以帮我吗?
更改于 26/6/2018:我自己偶然发现了解决方案。代码如下,将NAoffreq.x改为0,仍然可以进行计算,结果显示在最后三列:
B <- function(frame1, frame2, column){
bframe$freq.x[is.na(bframe$freq.x)] <- 0
bframe <- merge(frame 1, frame2, by = column, all = TRUE)
bframe$result <- bframe$freq.x - bframe$freq.y
bframe$percentage <- (bframe$result/bframe$freq.y)*100
return(bframe)
}
B(DT2_1, 2_1, "BurgS")
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的错误并找到了另一个解决方案。
代替:
bframe[is.na(bframe)] <- 0
尝试在 is.na 函数后添加逗号:
bframe[is.na(bframe), ] <- 0
这对我来说非常有效!