unlist my words into a df but keep all other columns?

Viewed 48

I have a bunch of sentences that match up with a date and unique identifier. I want to make each row a new word, but keep it matched up with the date and unique identifier. So

| I am happy   | 24/12  | 3 |

Will change to

| I | 24/12 | 3 |
| am | 24/12 | 3 |
| happy | 24/12 | 3 |

I need it in data frame form.

4 Answers

Try this:

library(dplyr)
library(tidyr)
#Data
df <- data.frame(val='I am happy | 24/12 | 3',stringsAsFactors = F)
#Code
new <- df %>% separate(val,into = paste0('V',1:3),sep='\\|') %>%
  mutate(across(everything(),~trimws(.))) %>%
  separate_rows(V1,sep = ' ') %>%
  mutate(V3=as.numeric(V3))

Output:

# A tibble: 3 x 3
  V1    V2       V3
  <chr> <chr> <dbl>
1 I     24/12     3
2 am    24/12     3
3 happy 24/12     3

I guess you can try unnest + fread

unnest(
  fread(text = paste0(s, "\n"))[
    , V1 := .(strsplit(V1, " "))
  ], V1
)

which gives

# A tibble: 3 x 3
  V1    V2       V3
  <chr> <chr> <int>
1 I     24/12     3
2 am    24/12     3
3 happy 24/12     3

Data

s <- "I am happy | 24/12 | 3"

We can just use separate_rows

library(tidyr)
separate_rows(df, V1)

-output

# A tibble: 3 x 3
#  V1    V2       V3
#  <chr> <chr> <int>
#1 I     24/12     3
#2 am    24/12     3
#3 happy 24/12     3

data

df <- structure(list(V1 = "I am happy", V2 = "24/12", V3 = 3L), 
      class = "data.frame", row.names = c(NA, -1L))

If your dataframe is like :

df <- structure(list(V1 = "I am happy", V2 = "24/12", V3 = 3L), 
      class = "data.frame", row.names = c(NA, -1L))
df
#          V1    V2 V3
#1 I am happy 24/12  3

You can use unnest_tokens from tidytext.

df1 <- tidytext::unnest_tokens(df, V1, V1, to_lower = FALSE)
df1

#       V1    V2 V3
#1       I 24/12  3
#1.1    am 24/12  3
#1.2 happy 24/12  3
Related