Home > database >  I have two columns, if one column has a certain word in a row, I'd like the other column to add
I have two columns, if one column has a certain word in a row, I'd like the other column to add

Time:03-02

I have a column with string values and a column with numeric values. I want to add to the numeric value of each row if the string column has a certain word in it

For example:

stringColumn  numericColumn 
----------------------------
yes            5
no             7
no             3
yes            4

The numericColumn already has random numbers in it, but after running the code it should add 1 point to the numericColumn if the stringColumn = 'yes'.

So the dataset would end up looking like this

stringColumn  numericColumn 
----------------------------
yes            6
no             7
no             3
yes            5

CodePudding user response:

You can edit the numericColumn by using an ifelse statement inside mutate. So, if yes is detected (via str_detect) in the stringColumn, then add 1 to the number in the numericColumn and if not (i.e., no), then just return numericColumn.

library(tidyverse)

df %>%
  mutate(numericColumn = ifelse(
    str_detect(stringColumn, "yes"),
    numericColumn   1,
    numericColumn
  ))

Output

  stringColumn numericColumn
1          yes             6
2           no             7
3           no             3
4          yes             5

Or in base R:

df$numericColumn <-
  ifelse(grepl("yes", df$stringColumn),
         df$numericColumn   1,
         df$numericColumn)

Data

df <- structure(list(stringColumn = c("yes", "no", "no", "yes"), numericColumn = c(5L, 
7L, 3L, 4L)), class = "data.frame", row.names = c(NA, -4L))

CodePudding user response:

There are lots of ways of getting to the answer you want, but here is my take on a tidyverse version. The conditional statements are made within case_when() that is used inside mutate(). It's worth reading into what case_when() does since it'll come in handy for various uses.

library(tidyverse)

example_df <- tibble(
  stringColumn = c("yes", "no", "no", "yes"),
  numericColumn = c(5,7,3,4)
)

results_table <- example_df %>%
  mutate(
    Updated_column = case_when(
      stringColumn == "yes" ~ numericColumn   1,
      TRUE ~ numericColumn
    )
  )


# option 1: print to console 
results_table 

# option 1.2: a tidier way to view on the console
glimpse(results_table)

# option 2: view on RStudio 
View(results_table)

# option 3: save as file (eg. .csv format)
write_csv(results_table, "path/to/folder/my_results.csv")
  • Related