I need to change a row where if I have an n/a or null, I get a 0 and if I have a character in it, I get a 1, I am drawing a blank on it, when I tried the replace on is.na_replace no luck.
I have the following in the column
"" "h" "t" "tp" "tb" "p" "b" "ht" "v" "hb" "et" "hp" "tv" "e/s" "bp"
"e" "htp" "eb" "hv" "etb" "he"
any ideas?
CodePudding user response:
vec <- c("", "h", "t", "tp")
(!is.na(vec) & nzchar(vec))
# [1] 0 1 1 1
nzchar(vec)
returnslogical
(true/false) based on whether there are any characters in each string; it is analogous tonchar(vec) > 0
, wherenchar("")
is 0;- however, if any of
vec
areNA
, they are silently converted to"NA"
internally, which has 2 characters in it; to preclude this, we preface that with!is.na(vec)
(...)
where...
is a logical expression is a shortcut for converting a logical vector to integer. SeeTRUE
andFALSE
.
It could also have been done with an ifelse
(or replace
or dplyr::if_else
or data.table::fifelse
), which in this case is fine, but I don't think it adds much value while it does add overhead to the call-stack.
CodePudding user response:
Another way you can do this with dplyr
:
df <- data.frame(s = c("", "hdsa", "t", "tp", "tb"))
df %>%
mutate(new_col = ifelse(
nchar(s) > 0,
1,
0
))
s new_col
1 0
2 hdsa 1
3 t 1
4 tp 1
5 tb 1
CodePudding user response:
Here is a tidyverse approach:
library(dplyr)
library(stringr)
library(tibble)
vec <- c("", "h", "t", NA)
tibble(vec) %>%
mutate(new_col = case_when(vec == "" | is.na(vec) ~ "0",
str_detect(vec, '[A-Za-z]') ~ "1"))
vec new_col
<chr> <chr>
1 "" 0
2 "h" 1
3 "t" 1
4 NA 0
CodePudding user response:
Try this
#first rty this,it will replace NA to 0
df%>% mutate_at(vars(column,row with na),~replace(.,is.na(.), 0))
and use gsub function to replace characters with what you want
see samples below
# consider a string "Python and java"
# replace the character 'a' in "Python and java"
# with "M"
print(sub("a", "M", "Python and java") )
you get "Python and java"
I hope it works