Home > Back-end >  Convert numbers into strings while leaving characters untouched in R
Convert numbers into strings while leaving characters untouched in R

Time:10-13

I have a vector that looks like this:

> vector <- c("1","2","0", "10", "name", "hello")

I want to convert it so that each numeric character becomes a string, leaving actual strings unaffected.

[1] "test" "test" "test" "test" "name" "hello"

How can I do this?

CodePudding user response:

sub("^\\d $", "test", vector)
[1] "test"  "test"  "test"  "test"  "name"  "hello"

str_replace(vector, "^[0-9] $", "test")
[1] "test"  "test"  "test"  "test"  "name"  "hello"

CodePudding user response:

One option with warnings is to convert to integer and check for NA values with is.na and do the assignment

vector[!is.na(as.integer(vector))] <- "test"

-output

> vector
[1] "test"  "test"  "test"  "test"  "name"  "hello"

The idea is that non-NA elements returns NA when convert to numeric and this is captured as a logical vector with is.na to subset the original vector and then do the assignment


Another option without warnings is also possible with a regex i.e. find the elements where there are only digits or dot from the start (^) to the end ($) and replace those with 'test'

vector[grep("^[0-9.] $", vector)] <- "test"

CodePudding user response:

library(stringr)

str_replace_all(vector, "[0-9].*", 'test')
[1] "test"  "test"  "test"  "test"  "name"  "hello"
  •  Tags:  
  • r
  • Related