Marwah Al-kaabi
Marwah Al-kaabi

Reputation: 405

Creating new column with condition

I have this data set:

ID Type Frequency
1  A    0.136546185
2  A    0.228915663
3  B    0.006024096
4  C    0.008032129

I want to create a new column that change the Frequency vaules less than 0.00 in to "other" and keep other information as it is. Like this :

ID Type Frequency       New_Frequency
1  A    0.136546185     0.136546185  
2  A    0.228915663     0.228915663
3  B    0.006024096     other
4  C    0.008032129     other

I used mutate but I dont know how to keep the original frequency bigger than 0.00. Can you please help me?

Upvotes: 0

Views: 52

Answers (3)

Elin
Elin

Reputation: 6755

You can't achieve what you want in base r because you cannot mix characters and numerics in the same vector. If you are willing to convert everything to characters the other answers will work. If you want to keep them numeric you need to use NA rather than "other". You can also try the labelled package which allows something like SPSS labels or SAS formats on numeric data.

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

You can use ifelse

transform(df, Frequency = ifelse(Frequency < 0.01, 'Other', Frequency))

#  ID Type   Frequency
#1  1    A 0.136546185
#2  2    A 0.228915663
#3  3    B       Other
#4  4    C       Other

Note that Frequency column is now character since a column can have data of only one type.

Upvotes: 1

Brigadeiro
Brigadeiro

Reputation: 2945

Using mutate():

library(dplyr)

d <- tibble(ID = 1:4,
            Type = c("A", "A", "B", "C"),
            Frequency = c(0.136546185, 0.228915663, 0.006024096, 0.008032129))

d %>%
  mutate(New_Frequency = case_when(Frequency < .01 ~ "other",
                                   TRUE ~ as.character(Frequency)))

Upvotes: 1

Related Questions