8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Tidydata vs 神Excel: Rで1つのセルに入力された複数項目を分割処理する

Last updated at Posted at 2020-01-15

エクセルなどで、1セル中に複数の項目が入ったデータを処理することがあると思います。基本的にはdplyr::separateで処理すればいいと思いますが、格納されている数が不定な場合、また何個あるかわからない場合に上手く処理できる関数を知らなかったのです。

r-wakalangで聞いたら、Rおじさんたちが優しく教えてくれました。備忘録も兼ねて記事にしておきます。

data.frame(Subject = c("A","B","C","D"),
   Value = c("a+b+c", "c","b+c", "a+b+c+d+e"))

str_split()からのunnest()

demo <- data.frame(Subject = c("A","B","C","D"),
				   Value = c("a+b+c", "c","b+c", "a+b+c+d+e"))
demo %>%
group_by(Subject) %>% 
mutate(Value = str_split(Value, '\\+')) %>% 
unnest()

# Groups:   Subject [4]
   Subject Value
   <fct>   <chr>
 1 A       a    
 2 A       b    
 3 A       c    
 4 B       c    
 5 C       b    
 6 C       c    
 7 D       a    
 8 D       b    
 9 D       c    
10 D       d    
11 D       e  

tidyr::separate_rows()

library(tidyverse)
demo <- data.frame(Subject = c("A","B","C","D"),
                   Value = c("a+b+c", "c","b+c", "a+b+c+d+e"))

demo %>% 
  tidyr::separate_rows(Value, sep = "\\+")

   Subject Value
1        A     a
2        A     b
3        A     c
4        B     c
5        C     b
6        C     c
7        D     a
8        D     b
9        D     c
10       D     d
11       D     e

教えていただいた方々、どうもありがとうございました!

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?