How to replace values in df that are NOT fulfilling condition

69 Views Asked by At

I am trying to clean my data and can't find a way to replace values that are not according to my conditions like in the following example:

df1<-  data.frame(
A=c("a","b","c"),
Ch=c("c1","xyz","c2"),
val=paste0("x",1:3),  stringsAsFactors = FALSE)

all values that are different than c1, c2 I want to change into "other".

I tried:

for( i in 1:length(df)
if (df[i,2]==c1 | c2){
stay same vaue?!?
} else df[i,2] <- "other"

which did not work.

Any suggestions?

2

There are 2 best solutions below

1
On

For replicability:

df1<-
tibble(
  A=c("a","b","c"),
  Ch=c("c1","xyz","c2"),
  val=paste0("x",1:3)
)

If you are trying to do it across all columns:

library(tidyverse)

df1%>%mutate_all(list(~ifelse(.=="c1"|.=="c2",.,"other")))

Base R solution:

data.frame(
sapply(
  df1,
  function(x)ifelse(x=="c1"|x=="c2",x,"other")
 )
)
0
On

Here is another base R solution if you want to change only one column

df1<-  data.frame(
A=c("a","b","c"),
Ch=c("c1","xyz","c2"),
val=paste0("x",1:3),  stringsAsFactors = FALSE)

df1$Ch[df1$Ch!="c1" & df1$Ch!="c2"] <- "other"

This will replace the column Ch only