0

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?

markus
  • 25,843
  • 5
  • 39
  • 58
antonina
  • 109
  • 8

2 Answers2

3

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")
 )
)
costebk08
  • 1,299
  • 4
  • 17
  • 42
  • 3
    In base R, you can just do `df1[df1!="c1" & df1!="c2"] <- "other"`, assuming that those columns are strings and not factors. – ulfelder Dec 09 '19 at 21:07
0

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

XXavier
  • 1,206
  • 1
  • 10
  • 14