Ak204
Ak204

Reputation: 63

Replacing multiple values in a column of a data frame based on condition

here is data set of weight

enter image description here

I have to replace values in weight column based on following conditon

  1. if weight < 7 then replace values with a
  2. if weight > = 7 and <8 replace values with b
  3. if weight >= 8 replace with c

Upvotes: 0

Views: 5118

Answers (2)

biomiha
biomiha

Reputation: 1422

You could use dplyr as well to either replace the same column (give it the same name) or add (by giving it a new name). The code below replaces the existing "weight" column.

library(dplyr)
yourdata%>%mutate(
          weight=ifelse(weight <7, "a", ifelse(weight >=7 & weight < 8, "b", "c")))

In future can you provide a reproducible example of your data that's not a jpeg: How to make a great R reproducible example?

Upvotes: 2

akrun
akrun

Reputation: 887118

One option is ifelse

df1$New <- with(df1, ifelse(weight <7, "a", ifelse(weight >=7 & weight < 8, "b", "c")))
df1$New
#[1] "a" "c" "c" "a" "c" "b" "c"

or we can use cut if there are many groups

with(df1, as.character(cut(weight, breaks = c(-Inf, 7, 8, Inf),
                         labels = c('a', 'b', 'c'))))
#[1] "a" "c" "c" "a" "c" "b" "c"

data

set.seed(24)
df1 <- data.frame(weight = rnorm(7, 7, 3))

Upvotes: 2

Related Questions