2

I am pretty much new to R . I am trying to take out the value with the ; and add it as a value in a new column until it encounters another value with ;. Now that value preceeding ; will be the value in that new column.

thank you!

enter image description here

Result:

enter image description here

Jaap
  • 81,064
  • 34
  • 182
  • 193
Sankar
  • 23
  • 2
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Jun 07 '18 at 13:22

2 Answers2

1

We create a group based on the occurence of ; and then get the first element of 'v1' as a new column

library(dplyr)
df1 %>%
    group_by(grp = cumsum(grepl(";", v1))) %>%
    mutate(new = as.numeric(sub(";", "", first(v1)))) %>% 
    filter(!grepl(";", v1)) %>%
    ungroup %>%
    select(-grp)
# A tibble: 9 x 2
#  v1         new
#  <chr>    <dbl>
#1 12345       10
#2 67890       10
#3 11121314    10
#4 85642       10
#5 19654       10
#6 5642        11
#7 9987        11
#8 22365       11
#9 5589        13

data

df1 <- data.frame(v1 = c('10;', 12345, 67890, 11121314, 85642, 19654, 
   '11;', 5642, 9987, 22365, '13;', 5589), stringsAsFactors = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Another solution using fill from tidyr (with @akrun's data):

library(dplyr)
library(tidyr)

df1 %>%
  mutate(v2 = if_else(grepl(';', v1), as.numeric(sub(';', '', v1)), NA_real_)) %>%
  fill(v2) %>%
  filter(!grepl(';', v1))

Result:

        v1 v2
1    12345 10
2    67890 10
3 11121314 10
4    85642 10
5    19654 10
6     5642 11
7     9987 11
8    22365 11
9     5589 13
acylam
  • 18,231
  • 5
  • 36
  • 45