0

Let say I have such a dataframe(df):

header
---------
23.43
1,23
34.54
56.2
5,5

Some numbers are with dot(.) and some are with comma(,).

I want to split this column into two columns according to dots and commas into a new dataframe(df2) like:

header1  header2
------- --------
23       43
1        23
34       54
56       2
5        5

How can I do this using R? I will be very glad for any help. Thanks a lot.

Thanks a lot for the answers and for your time.

What about if the separators are in more than one character. For example:

header
---------
23 ab 43
1 ca 23
34 ab 54
56 ca 2
5 ca 5

How can we split this dataframe into two columns according to seperators "ab" and "ca"?

oercim
  • 1,808
  • 2
  • 17
  • 34

1 Answers1

4

Based on @alistaire's comment you can combine strsplit (split the strings), do.call and rbind (bind results rowise):

df <- data.frame(header=c("23.43", "1,23", "34.54", "56.2", "5,5"),
                 stringsAsFactors = FALSE)


r <- as.data.frame(do.call(rbind, strsplit(df$header, "[,.]")),
                   stringsAsFactors = FALSE)
colnames(r) <- c("header1", "header2")
r[] <- lapply(r, type.convert)
r
#   header1 header2
# 1      23      43
# 2       1      23
# 3      34      54
# 4      56       2
# 5       5       5
sgibb
  • 25,396
  • 3
  • 68
  • 74