R:删除每列中的NULL,同时保持列中的顺序

xjreopfe  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(81)

我有一个R中包含NULL或编号的 Dataframe :示例:

people1 <- c("Variety 1", "Variety 2", "Variety 3", "Variety 4", "Variety 5")
people2 <- c("Variety 4", "Variety 3", "Variety 2", "Variety 1", "NULL")
people3 <- c("Variety 3", "Variety 2", "NULL", "Variety 4", "Variety 1")
df2 <- data.frame(people1, people2, people3)

对于每一列,如果有NULL或NA,我希望将它们删除,并将下一项上移以进行替换,这样列可以以NULL结尾,但不会在中间。
你能帮忙吗?谢谢!

mnowg1ta

mnowg1ta1#

请注意,在我回答问题后,该问题发生了变化,原始问题的答案位于底部的"旧问题"下。新问题的答案为:

replace(df2, TRUE, lapply(df2, function(x) c(x[x != "NULL"], x[x == "NULL"])))

给出:

people1   people2   people3
1 Variety 1 Variety 4 Variety 3
2 Variety 2 Variety 3 Variety 2
3 Variety 3 Variety 2 Variety 4
4 Variety 4 Variety 1 Variety 1
5 Variety 5      NULL      NULL

旧的

将"NULL"值转换为NA,并使用na.locf(最后一次出现的值结转)。如果有多个连续的"NULL"值,也可以使用此方法。

library(zoo)

m <- as.matrix(df2)
replace(df2, TRUE, na.locf(ifelse(m == "NULL", NA, m)))

给出:

people1   people2   people3
1 Variety 1 Variety 4 Variety 3
2 Variety 2 Variety 3 Variety 2
3 Variety 3 Variety 2 Variety 2
4 Variety 4 Variety 1 Variety 4
5 Variety 5 Variety 1 Variety 1
mepcadol

mepcadol2#

df3 <- data.frame(
  people1 = c(people1[people1 != "NULL"], people1[people1=="NULL"]),
  people2 = c(people2[people2 != "NULL"], people2[people2=="NULL"]),
  people3 = c(people3[people3 != "NULL"], people3[people3=="NULL"])
        )

将适用于“NULL”字符串。

> df3
    people1   people2   people3
1 Variety 1 Variety 4 Variety 3
2 Variety 2 Variety 3 Variety 2
3 Variety 3 Variety 2 Variety 4
4 Variety 4 Variety 1 Variety 1
5 Variety 5      NULL      NULL

相关问题