Reputation: 175
i am trying to change the values in column Name with VAN with ignoring NA values.
df <- data.frame(Name = c("ABC","VAN","KLA","DCA", "GOL",NA, "MNA",NA, "VAN","BAN",NA,"MHA",NA,"KLA"))
df <- df %>% mutate(Name=replace(.,!is.na(Name),"VAN"))
Upvotes: 1
Views: 41
Reputation: 389235
You can use [<-
to assign the value where Name
is not NA
.
df$Name[!is.na(df$Name)] <- 'VAN'
df
# Name
#1 VAN
#2 VAN
#3 VAN
#4 VAN
#5 VAN
#6 <NA>
#7 VAN
#8 <NA>
#9 VAN
#10 VAN
#11 <NA>
#12 VAN
#13 <NA>
#14 VAN
Upvotes: 0
Reputation: 887851
The issue is that the OP used .
and .
refers to the whole dataset. We just need to specify the column name 'Name'
library(dplyr)
df <- df %>%
mutate(Name=replace(Name,!is.na(Name),"VAN"))
-output
df
Name
1 VAN
2 VAN
3 VAN
4 VAN
5 VAN
6 <NA>
7 VAN
8 <NA>
9 VAN
10 VAN
11 <NA>
12 VAN
13 <NA>
14 VAN
If there are more than one columns, do it with across
to loop over the columns
df <- df %>%
mutate(across(everything(), ~ replace(., !is.na(.), "VAN")))
Here everything()
implies all the columns of the dataset
Upvotes: 1
Reputation: 7116
library(tidyverse)
library(stringr)
df <- data.frame(Name = c("ABC","VAN","KLA","DCA", "GOL",NA, "MNA",NA, "VAN","BAN",NA,"MHA",NA,"KLA"))
head(df)
#> Name
#> 1 ABC
#> 2 VAN
#> 3 KLA
#> 4 DCA
#> 5 GOL
#> 6 <NA>
mutate(df, Name = str_replace(Name, "^.*$", 'VAN'))
#> Name
#> 1 VAN
#> 2 VAN
#> 3 VAN
#> 4 VAN
#> 5 VAN
#> 6 <NA>
#> 7 VAN
#> 8 <NA>
#> 9 VAN
#> 10 VAN
#> 11 <NA>
#> 12 VAN
#> 13 <NA>
#> 14 VAN
Created on 2021-06-07 by the reprex package (v2.0.0)
Upvotes: 1