删除数据帧中所有剩余的NA,并向左移动已清理的行 [英] Dropping all left NAs in a dataframe and left shifting the cleaned rows
问题描述
我有以下数据框dat
,该数据框在某些行的开头显示了特定于行的NA:
I have the following dataframe dat
, which presents a row-specific number of NAs at the beginning of some of its rows:
dat <- as.data.frame(rbind(c(NA,NA,1,3,5,NA,NA,NA), c(NA,1:3,6:8,NA), c(1:7,NA)))
dat
# V1 V2 V3 V4 V5 V6 V7 V8
# NA NA 1 3 5 NA NA NA
# NA 1 2 3 6 7 8 NA
# 1 NA 2 3 4 5 6 NA
我的目的是删除每行开头的所有NA,并左移行值(相应地在已移动行的末尾添加NA,以保持其长度不变).
My aim is to delete all the NAs at the beginning of each row and to left shift the row values (adding NAs at the end of the shifted rows accordingly, in order to keep their length constant).
以下代码按预期工作:
for (i in 1:nrow(dat)) {
if (is.na(dat[i,1])==TRUE) {
dat1 <- dat[i, min(which(!is.na(dat[i,]))):length(dat[i,])]
dat[i,] <- data.frame( dat1, t(rep(NA, ncol(dat)-length(dat1))) )
}
}
dat
返回:
# V1 V2 V3 V4 V5 V6 V7 V8
# 1 3 5 NA NA NA NA NA
# 1 2 3 6 7 8 NA NA
# 1 NA 2 3 4 5 6 NA
我想知道还有没有使用for循环和使用tail
函数的更直接的方法.
I was wondering whther there is a more direct way to do so without using a for-loop and by using the tail
function.
关于最后一点,通过使用min(which(!is.na(dat[1,])))
,结果为3
,如预期的那样.但是,如果我键入tail(dat[1,],min(which(!is.na(dat[1,]))))
,结果将是相同的初始行,而我不明白为什么.
With respect to this last point, by using min(which(!is.na(dat[1,])))
the result is 3
, as expected. But then if I type tail(dat[1,],min(which(!is.na(dat[1,]))))
the result is the same initial row, and I don't understand why..
非常感谢您提出的建议.
Thank you very much for anu suggestion.
推荐答案
我认为您不能无循环执行此操作.
I don't think you can do this without a loop.
dat <- as.data.frame(rbind(c(NA,NA,1,3,5,NA,NA,NA), c(NA,1:3,6:8,NA), c(1:7,NA)))
dat[3,2] <- NA
# V1 V2 V3 V4 V5 V6 V7 V8
# 1 NA NA 1 3 5 NA NA NA
# 2 NA 1 2 3 6 7 8 NA
# 3 1 NA 3 4 5 6 7 NA
t(apply(dat, 1, function(x) {
if (is.na(x[1])) {
y <- x[-seq_len(which.min(is.na(x))-1)]
length(y) <- length(x)
y
} else x
}))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 3 5 NA NA NA NA NA
#[2,] 1 2 3 6 7 8 NA NA
#[3,] 1 NA 3 4 5 6 7 NA
然后根据需要将矩阵转换为data.frame.
Then turn the matrix into a data.frame if you must.
这篇关于删除数据帧中所有剩余的NA,并向左移动已清理的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!