gpt4 book ai didi

r - 将NA移到数据框中每一列的末尾

转载 作者:行者123 更新时间:2023-12-04 09:18:12 24 4
gpt4 key购买 nike

我有这样一个数据框:

df <- structure(list(a = c(NA, NA, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), b = c(NA, NA, NA, 1L, 2L, 3L, 4L, 5L, 6L, 7L), d = c(NA, NA, NA, NA, 1L, 2L, 3L, 4L, 5L, 6L)), .Names = c("a", "b", "d"), row.names = c(NA, -10L), class = "data.frame")

> df
a b d
1 NA NA NA
2 NA NA NA
3 1 NA NA
4 2 1 NA
5 3 2 1
6 4 3 2
7 5 4 3
8 6 5 4
9 7 6 5
10 8 7 6
在每列中,我想将非 NA值向上移动,并将 NA移至末尾:
> df.out
a b d
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 NA
8 8 NA NA
9 NA NA NA
10 NA NA NA
更新以使我的问题更清楚..
df <- structure(list(a = c(NA, NA, 1, 5, 34, 7, 3, 5, 8, 4), b = c(NA, 
NA, NA, 57, 2, 7, 9, 5, 12, 100), d = c(NA, NA, NA, NA, 5, 7,
2, 8, 2, 5)), .Names = c("a", "b", "d"), row.names = c(NA, -10L
), class = "data.frame")

> df
a b d
1 NA NA NA
2 NA NA NA
3 1 NA NA
4 5 57 NA
5 34 2 5
6 7 7 7
7 3 9 2
8 5 5 8
9 8 12 2
10 4 100 5
应导致:
    a   b  d
1 1 57 5
2 5 2 7
3 34 7 2
4 7 9 8
5 3 5 2
6 5 12 5
7 8 100 NA
8 4 NA NA
9 NA NA NA
10 NA NA NA
似乎是一项简单的任务,但我被困在从何开始。您能帮上忙吗?

最佳答案

在完全误解了问题之后,这是我的最终答案:

# named after beetroot for being the first to ever need this functionality
beetroot <- function(x) {
# count NA
num.na <- sum(is.na(x))
# remove NA
x <- x[!is.na(x)]
# glue the number of NAs at the end
x <- c(x, rep(NA, num.na))
return(x)
}

# apply beetroot over each column in the dataframe
as.data.frame(lapply(df, beetroot))

它将对NA进行计数,删除NA,并在数据帧中的每一列的底部粘贴NA。

关于r - 将NA移到数据框中每一列的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25869011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com