How to replace a value in a data frame based on a conditional 'If' statement?

0 votes

I tried replacing all of the times that B appears with b.

Consider the code below, to do the following:

junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12])
colnames(junk) <- c("alpha", "value")

this provides:

   alpha value
1   A    a
2   B    b
3   C    c
4   D    d
5   A    e
6   B    f
7   C    g
8   D    h
9   A    i
10  B    j
11  C    k
12  D    l

An initial attempt was to use a for and if statements like so:

for(i in junk$alpha) if(i %in% "B") junk$alpha <- "b"

but this replaces all of the values of junk$alpha with b.

 I know why this is doing this but I can't seem to get it to replace only those cases of junk$alpha where the original value was B.

Jun 6, 2018 in Data Analytics by DataKing99
• 8,130 points
677 views

1 answer to this question.

0 votes

It's easier to convert alpha to characters and then make the change:

junk$alpha <- as.character(junk$alpha)

junk$alpha[junk$alpha == "B"] <- "b"

junk$alpha <- as.factor(junk$alpha)

answered Jun 6, 2018 by darklord
• 6,190 points

Related Questions In Data Analytics

0 votes
1 answer
0 votes
2 answers

How to arrange a data set in ascending order based on a variable?

In your case it'll be, orderedviews = arrange(movie_views, ...READ MORE

answered Nov 27, 2018 in Data Analytics by Kalgi
• 46,320 points
54 views
0 votes
2 answers
0 votes
1 answer

How to replace all occurrences of a character in a character column in a data frame in R

If you used sub() to replace the ...READ MORE

answered Jun 28 in Data Analytics by anonymous
• 32,280 points
155 views
0 votes
1 answer

How to write a custom function which will replace all the missing values in a vector with the mean of values in R?

Consider this vector: a<-c(1,2,3,NA,4,5,NA,NA) Write the function to impute ...READ MORE

answered Jul 4, 2018 in Data Analytics by CodingByHeart77
• 3,690 points
221 views
0 votes
1 answer

Big Data transformations with R

Dear Koushik, Hope you are doing great. You can ...READ MORE

answered Dec 17, 2017 in Data Analytics by Sudhir
• 1,610 points
68 views
0 votes
2 answers

Transforming a key/value string into distinct rows in R

We would start off by loading the ...READ MORE

answered Mar 26, 2018 in Data Analytics by Bharani
• 4,560 points
86 views
0 votes
1 answer

Finding frequency of observations in R

You can use the "dplyr" package to ...READ MORE

answered Mar 26, 2018 in Data Analytics by Bharani
• 4,560 points
258 views
0 votes
2 answers

How to sort a data frame by columns in R?

You can use dplyr function arrange() like ...READ MORE

answered Aug 21 in Data Analytics by anonymous
• 32,280 points
169 views
0 votes
2 answers

How to remove rows with missing values (NAs) in a data frame?

Hi, The below code returns rows without ...READ MORE

answered Aug 20 in Data Analytics by anonymous
• 32,280 points
6,208 views