How to manipulate data in R?

Viewed 42

I have a data set something like this:

data <- tribble(
  ~id,                 ~value,
   '311321 333 333',     20,
   '18 939 4244',         0,
   '999 3838 4242',       1,
  )

Now, I want to get only the first item in id column and then return the variable of value to 1 if it is greater than 0. Here is the desired data:

desired_data <- tribble(
  ~new_id,  ~value,  ~new_value,
  '311321',  20,         1,
  '18',       0,         0,
  '999',      1,         1,  
)

Any idea how to do it?

1 Answers

An easier option is to remove the substring from the space onwards

library(dplyr)
library(stringr)
data %>% 
    mutate(id = str_remove(id, "\\s+.*"), new_value = as.integer(value > 0))

Or another option is to use parse_number which extracts the first number

data %>%
  mutate(id = readr::parse_number(id), new_value = +(value > 0) )

Or with word

data %>%
  mutate(id = word(id, 1), new_value = ifelse(value > 0, 1, 0))
# A tibble: 3 x 3
#  id     value new_value
#  <chr>  <dbl>     <dbl>
#1 311321    20         1
#2 18         0         0
#3 999        1         1
Related