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$
2
  • 1
    $\begingroup$ Do you have a dummy dataframe that you can provide? $\endgroup$
    – n1k31t4
    Commented Sep 19, 2018 at 19:40
  • $\begingroup$ df[is.numeric(df)]="string". $\endgroup$ Commented Sep 20, 2018 at 6:31

3 Answers 3

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>
$\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')
$\endgroup$
0
$\begingroup$

For those who want to replace the values in the whole dataframe:

df[!is.na(df)] <- 'NOTMISSING'

I wanted to make this as a comment to the answer by @eg-r, but I do not have enough reputation.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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