我正在尝试创建一个用平均值/中值替换NA的函数。
以下代码正在运行 - [mydata是一个数据框]
data = mydata
type = mean
{
for (i in which(sapply(data, is.numeric))){
data[is.na(data[, i]), i] <- type(data[, i], na.rm = TRUE)
}
}
为什么以下代码在我将其包装在函数中时不起作用?
impute <- function(data, type) {
for (i in which(sapply(data, is.numeric))) {
data[is.na(data[, i]), i] <- type(data[, i], na.rm = TRUE)
}
}
impute(data=mydata,mean)
答案 0 :(得分:1)
要使@ Frank的注释明确,您需要显式返回数据框,如:
impute <- function(data, type) {
for (i in which(sapply(data, is.numeric))) {
data[is.na(data[, i]), i] <- type(data[, i], na.rm = TRUE)
}
data
}
或隐含地,如:
data
并更新您的data.frame newdata <- impute(data,mean)
,然后您可以像这样调用您的impute函数:
for
如果你想避免impute <- function(data, type)
sapply(data,
function(x)
if(is.numeric(x) && any(is.na(x)) && !all(is.na(x)))
x[is.na(x)] <- type(x[!is.na(x)])
x)
循环,可以采取以下方式:
import java.io.*;
public class Exec {
public static void main(String args[]) {
try {
String line;
Process p = Runtime.getRuntime().exec(args[0]);
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
}