1

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"))

2
  • You need df %>% mutate(Name=replace(Name,!is.na(Name),"VAN")). i.e. replace the . with Name Commented Jun 8, 2021 at 2:11
  • 1
    yes its working , Thanks Commented Jun 8, 2021 at 2:41

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
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)

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.