Sankar
Sankar

Reputation: 23

R column splitting

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

Upvotes: 2

Views: 37

Answers (2)

acylam
acylam

Reputation: 18681

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

Upvotes: 1

akrun
akrun

Reputation: 887183

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)

Upvotes: 1

Related Questions