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?

1
  • Feel free to mark the answer as accepted if it does what you need it to do :) Commented Dec 10, 2019 at 3:54

2 Answers 2

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")
 )
)
Sign up to request clarification or add additional context in comments.

1 Comment

In base R, you can just do df1[df1!="c1" & df1!="c2"] <- "other", assuming that those columns are strings and not factors.
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

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.