Reputation: 125
Is there a way to replace dashes by NA
or zero without affecting negative values in a vector that resembles the following: c("-","-121512","123","-")
.
Upvotes: 2
Views: 470
Reputation: 887213
We can use na_if
library(dplyr)
na_if(v1, "-") %>%
as.numeric
#[1] NA -121512 123 NA
If it is a data.frame
library(tidyverse)
df1 %>%
mutate_all(na_if, "-") %>%
type_convert
v1 <- c("-","-121512","123","-")
Upvotes: 2
Reputation: 26343
Just do
x <- c("-","-121512","123","-")
x[x == "-"] <- NA
x
#[1] NA "-121512" "123" NA
If you need a numeric vector instead of character wrap x
in as.numeric()
.
If you want to replace all "-"
in a dataframe we can use the same logic
df1 <- data.frame(x = c("-","-121512","123","-"),
y = c("-","-121512","123","-"),
z = c("-","A","B","-"), stringsAsFactors = FALSE)
df1[df1 == "-"] <- NA
If you want numeric columns if appropriate then you type.convert
df1[] <- lapply(df1, type.convert, as.is = TRUE)
str(df1)
'data.frame': 4 obs. of 3 variables:
$ x: int NA -121512 123 NA
$ y: int NA -121512 123 NA
$ z: chr NA "A" "B" NA
Upvotes: 2