R-obert
R-obert

Reputation: 1039

Keep data frame size unchanged when subsetting values in R

I want to subset a data frame by dropping values but without dropping any columns.

Example

> df <- as.data.frame(rbind(c(1,2,3,4,5,6, 1), c(4,5,6,7,3,0, 0)))
> df
  V1 V2 V3 V4 V5 V6 V7
1  1  2  3  4  5  6  1
2  4  5  6  7  3  0  0

As expected, subsetting returns a smaller data frame:

> df[which(df[1,] > 2)]
  V3 V4 V5 V6
1  3  4  5  6
2  6  7  3  0

How do I have subset return the below data frame?

   V1 V2 V3 V4 V5 V6  V7
1  NA NA  3  4  5  6  NA
2  NA NA  6  7  3  0  NA

Upvotes: 0

Views: 150

Answers (1)

Anthony Damico
Anthony Damico

Reputation: 6104

you don't actually want to subset your data frame, you just want to blank out certain columns. so just reverse the logic inside your which command..

df[ , df[ 1 , ] <= 2]

# and set all of _those_ values to NA
df[ , df[ 1 , ] <= 2] <- NA

# look at the result
df

note: if your data frame already contains NAs in the first column, the <= will return an NA which is probably not what you want. just be sure whatever test you use doesn't return NA values.

Upvotes: 4

Related Questions