gpt4 book ai didi

当某些列在 R 中具有某些值时删除某些列

转载 作者:行者123 更新时间:2023-12-05 04:22:49 27 4
gpt4 key购买 nike

我需要删除其中具有特定值的某些列。

这是一个示例数据集:

df <- data.frame(var1 = c(1,2,3,4,5),
var2 = c("a","b","c","d","e"),
var3 = c("[Name A]","[Surname B]",NA, NA, NA),
var4 = c("[Name A]","[Surname B]",NA, NA, NA))


> df
var1 var2 var3 var4
1 1 a [Name A] [Name A]
2 2 b [Surname B] [Surname B]
3 3 c <NA> <NA>
4 4 d <NA> <NA>
5 5 e <NA> <NA>

var3var4[Name A][Surname B] 然后是 NA 当列具有这种模式时,我需要将其删除。

我怎样才能获得下面所需的数据集:

> df1
var1 var2
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e

最佳答案

index <- sapply(
df,
FUN = function(x){
ifelse(
x[[1]] == "[Name A]" & x[[2]] == "[Surname B]",
# modify this ifelse to match exactly what you want, e.g. certain number of NA, remainder of values are NA, etc
FALSE,
TRUE
)
}
)



index
# var1 var2 var3 var4
# TRUE TRUE FALSE FALSE



df[,index]
# var1 var2
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e

关于当某些列在 R 中具有某些值时删除某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73874849/

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