'I have two columns, if one column has a certain word in a row, I'd like the other column to add 1 point to the corresponding row
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
Solution 1:[1]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
