1

I'm trying to remove NA values in the columns of a data frame and trying to cbind the resulting vectors another data frame. Here's the code I'm using:

for (x in df_wide[4:8]) {
  a <- df_wide[[x]][!is.na(df_wide[[x]])]
  df <- cbind(df, a)
}

But I'm getting this error:

`Error in .subset2(x, i, exact = exact) : no such index at level 1`

I've also tried using apply function, but I got the same error.

`Error in .subset2(x, i, exact = exact) : no such index at level 1`
function (x, i, exact) 
if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact)

Can anyone please explain me why I'm getting this error and how can I fix it?

If you want to see the data frame, please refer to my previous question.

Thanks in advance.

Tpg333
  • 33
  • 5

2 Answers2

1

You only need to specify for (x in 4:8). Or you can can reference the column names, but right now you are using columns as indexes, which is only useful for integer columns (if that's your goal).

I don't think this way is the best way to go about solving your problem, though.

Max Candocia
  • 3,774
  • 27
  • 48
1

for (x in df_wide[4:8])

is putting the whole results in x. So x is equal to the whole vector of of that column. Ex: x <- df_wide[4], then x <- df_wide[5], then... etc.

a <- df_wide[[x]][!is.na(df_wide[[x]])]

is saying that you should find the vector of values (without header) of df_wide[[]] where the column number is the whole vector of df_wide[4] (or 5 or 6 or 7). But the column number (singular) cannot be all of the values in the x vector

A similar way to do this would be from this post you can search for using "omit NA values"

df_out <- df_wide[complete.cases(df_wide[,4:8]),]

which checks to see if the cases in columns 4:8 are complete, and then returns all columns in df_wide where the rows are complete cases.

Adam Sampson
  • 1,418
  • 1
  • 4
  • 14