0

I have a dataframe like this,

1 2 abc NA NA NA NA 
2 3 abd be f  NA NA
4 5 NA  NA NA NA NA)
....................

Now, I want to remove those rows which contain all NA's from column 3 onwards. I was doing something like this,,

df <- df[ !(is.na(df$X3)) |!(is.na(df$X4)) ..........]

However, the above command is too cumbersome for large number of columns

Also, after removing such rows, I want to rename the column names of my dataframe in a sequence, i.e. V1 V2 V3.... Till now, I was doing,

colnames(df) <- c("V1","V2","V3"...)

This is tedious for large number of columns. What can be a better method? Thanks!

chan chong
  • 135
  • 9
  • It is not clear if you want to remove rows of all NAs (rows which have only NA's after column 2) or all rows which contain *any* NAs after column 2. I'm guessing the latter based on your code. – Cotton.Rockwood Oct 05 '14 at 02:25

2 Answers2

2

Try

df <- df[rowSums(!is.na(df[, -c(1:2)])) != 0, ] # Remove rows which have NA's from column 3 on-wards
names(df) <- paste0("V", seq_along(df)) # Renaming the column names
df
##   V1 V2  V3   V4   V5 V6 V7
## 1  1  2 abc <NA> <NA> NA NA
## 2  2  3 abd   be    f NA NA
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
0

Another solution isdf <- df[complete.cases(df[ ,-(1:2)]), ]

df <- data.frame(c(1:4,NA), 3:7,c("abc","abd",NA,1:2),c(NA,"be",NA,"c", "d"),c(NA,"f",NA, "xy", "1.89"))

names(df) <- paste0("V", 1:ncol(df))
df
  V1 V2   V3   V4   V5
1  1  3  abc <NA> <NA>
2  2  4  abd   be    f
3  3  5 <NA> <NA> <NA>
4  4  6    1    c   xy
5  NA 7    2    d 1.89

df <- df[complete.cases(df[ ,-(1:2)]) , ]
df
  V1 V2  V3 V4   V5
2  2  4 abd be    f
4  4  6   1  c   xy
5  NA 7   2  d 1.89
Cotton.Rockwood
  • 1,601
  • 12
  • 29
  • Your solution removes columns rather than rows – David Arenburg Oct 05 '14 at 06:28
  • Actually, as you can see in the code I pasted, it removes rows. It checks for `complete.cases` in the df minus the first two rows. This returns a vector of TRUE/FALSE which is then used to subset the rows. – Cotton.Rockwood Oct 05 '14 at 16:11