Home > Net >  Remove a column in dataframe if a particular value meets a condition in R
Remove a column in dataframe if a particular value meets a condition in R

Time:04-08

After a lot of research, I'm struggling to do what should be straightforward in R. I am trying to delete columns only (not rows) if a value from a particular row and particular column meets a condition. For example I have a dataframe:

V1 <- c(1:2)
V2 <- c(2:3)
df1 <- data.frame(V1, V2)
V1 V2
1 2
2 3

I want to delete the entire column V2 if Row2/V2 is less than 4. As you can see in this example, the value in question is 3.

In which case I would be left with a dataframe that is equivalent to:

V1 <- c(1:2)
df1 <- data.frame(V1)
V1
1
2

Please help

CodePudding user response:

You probably want an if clause.

df1 <- if (df1[nrow(df1), 2] < 4) {
  df1[, -2, drop=FALSE]
} else {
  df1
}
df1
#   V1
# 1  1
# 2  2

CodePudding user response:

Without an if clause, you can do:

df1[seq_along(df1)[ifelse(df1$V2[2] < 4, -2, -(length(df1)   1))]]
#>   V1
#> 1  1
#> 2  2
  • Related