Tomikichi
Tomikichi

Reputation: 47

R data frame: Change value in 1 column depending on value in another

I have a data frame called nurse. At the moment it contains several columns but only one (nurse$word) is relevant at the moment. I want to create a new column named nurse$w.frequency which looks at the words in the nurse$word column and if it finds the one specified, I want it to change the corresponding nurse$w.frequency value to a specified integer.

nurse <- read.csv(...)


file   word         w.frequency
1      determining
2      journey
3      journey
4      serving
5      work
6      journey
...    ...

The word frequency for determining and journey, for instance, is 1590 and 4650 respectively. So it should look like the following:

file   word         w.frequency
1      determining  1590
2      journey      4650
3      journey      4650
4      serving
5      work
6      journey      4650
...    ...

I have tried it with the an ifelse statement (below) which seems to work, however, every time I try to change the actual word and frequency it overwrites the results from before.

nurse$w.frequency <- ifelse(nurse$word == "determining", nurse$w.frequency[nurse$word["determining"]] <- 1590, "")

Upvotes: 1

Views: 79

Answers (2)

Daniel O
Daniel O

Reputation: 4358

You could first initialise an empty column

nurse$w.frequency <- NA

then populated it with the data you want

nurse$w.frequency[nurse$word == "determining"] <- 1590
nurse$w.frequency[nurse$word == "journey"] <- 4650

Upvotes: 2

Matt
Matt

Reputation: 7385

Using dplyr:

nurse %>% 
  mutate(w.frequency = 
           case_when(
             word == "determining" ~ "1590",
             word == "journey" ~ "4650",
             TRUE ~ ""
           ))

Gives us:

         word w.frequency
1 determining        1590
2     journey        4650
3     journey        4650
4     serving            
5        work            
6     journey        4650

Data:

nurse <- data.frame(word = c("determining", "journey", "journey", "serving", "work", "journey"))

Upvotes: 1

Related Questions