Ann*_*nne 2 r function while-loop dataframe na
我正在数据框上应用 na.approx,如果 NA 恰好位于数据库的第一行或最后一行,则该方法将不起作用。
如何编写执行以下操作的函数:“当数据帧第一行的任何值为 NA 时,删除第一行”
数据框示例:
x1=x2=c(1,2,3,4,5,6,7,8,9,10,11,12)
x3=x4=c(NA,NA,3,4,5,6,NA,NA,NA,NA,11,12)
df=data.frame(x1,x2,x3,x4)
Run Code Online (Sandbox Code Playgroud)
此示例数据框的结果应如下所示:
result=df[-1:-2,]
Run Code Online (Sandbox Code Playgroud)
我当前的尝试看起来都类似于:
replace_na=function(df){
while(anyNA(df[1,])=TRUE){
df=df[-1,],
return(df)
}
#this is where I would apply the na.approx function to the data frame
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,谢谢!
您可以使用complete.cases. 使用cumsum,将删除第一个不完整的行:
df[cumsum(complete.cases(df)) != 0, ]
x1 x2 x3 x4
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 NA NA
8 8 8 NA NA
9 9 9 NA NA
10 10 10 NA NA
11 11 11 11 11
12 12 12 12 12
Run Code Online (Sandbox Code Playgroud)