1
$\begingroup$

I want to replace all numeric values in a column in my data frame with a string value. The following doesn't seem to work.

df <- within(df, myCol[is.numeric(myCol)] <- 'NOTMISSING')

Even though the df has some values as NA and others as numbers, all values are being replaced with NOTMISSING.

Also tried

df <- within(df, myCol[is_numeric(myCol)] <- 'NOTMISSING')

Any pointers highly appreciated.

$\endgroup$
  • 1
    $\begingroup$ Do you have a dummy dataframe that you can provide? $\endgroup$ – n1k31t4 Sep 19 '18 at 19:40
  • $\begingroup$ df[is.numeric(df)]="string". $\endgroup$ – user2974951 Sep 20 '18 at 6:31
1
$\begingroup$

From the documentation of is.numeric:

The default method for is.numeric returns TRUE if its argument is of mode "numeric" (type > "double" or type "integer") and not a factor, and FALSE otherwise.

So for a vector, is.numeric returns a single TRUE, it doesn't test each element as you might expect.

is.numeric(c(5, 4, 3))
[1] TRUE

is.numeric(c(5, 4, NA))
[1] TRUE

That's why either all or none of the values are changed to NOTMISSING.

@eg-r's fix is correct. Here's a tidyverse way to accomplish the same.

> df<-tibble(myCol=c(5, 4, NA))
> df
# A tibble: 3 x 1
  myCol
  <dbl>
1     5
2     4
3    NA
> df %>% mutate(myCol = ifelse(is.na(myCol), myCol, "NOTMISSING"))
# A tibble: 3 x 1
       myCol
       <chr>
1 NOTMISSING
2 NOTMISSING
3       <NA>
| improve this answer | |
$\endgroup$
0
$\begingroup$

NAs can be numeric (especially if the other values in that column are all numeric). Try this :

df$myCol = ifelse(is.numeric(df$myCol) & !is.na(df$myCol), "NOTMISSING", df$myCol)

Or if all you want to do is turn all values in that column that are not NA as that string, you can change your original code to :

df <- within(df, myCol[!is.na(myCol)] <- 'NOTMISSING')
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.