R:

2016-12-26 6 views
1

項目を、解析するベクトルに追加して数えて、私は映画についてのデータを分析しています。私はジャンルを解析して数えたいと思う。R:

私のデータは以下のようになります。

DATA1、DATA2、コメディ|アクション|アドベンチャー、DATA4は、私はジャンルの数をカウントしたい

をDATA5。私は、コードでアイテムを解析するために管理してきました:

genres <- as.data.frame(table(c(movies["genres"]))) 
# genres look like: 
#                Var1 Freq 
# 1                Action 11 
# 2             Action|Adventure 11 
# 3    Action|Adventure|Animation|Comedy|Crime|Family|Fantasy 1 
# ... 

# as you can see there are items which I need to parse 
# for 'debugging' purpose I managed to get 
strsplit(toString(genres$Var1[3]), split = "|", fixed = TRUE) 
# which results in below output: 
# [[1]] 
# [1] "Action" "Adventure" "Animation" "Comedy" "Crime"  "Family" "Fantasy" 

# My idea is to gather every parsed item into one object, then treated 
# that object "as.data.frame" so I could use 'Freq' from data.frame 
# please take a look at below code: 
genres <- as.data.frame(table(c(movies["genres"]))) 
list <- c() 
i = 1 
while(i <= length(genres$Var1)){ 
    parse <- strsplit(toString(genres$Var1[i]), split = "|", fixed = TRUE) 
    merge(list, parse) 
    i = i + 1 
} 

は、誰かがそれを達成するか、どのように私は簡単な方法でジャンルをカウントすることができますどのように良いアイデアを提供することができます。事前

答えて

1

で おかげで、これはあなたが探しているものでしょうか?

# split each row on "|" 
xx = strsplit(as.character(df$Var1), "|", fixed = TRUE) 

# based on the length of 'list of genre' in each row, repeat the corresponding 'Freq' 
yy = lapply(1:length(xx), function(x) rep(df$Freq[x], length(xx[[x]]))) 

df1 = data.frame(genre = unlist(xx), freq = unlist(yy)) 

library(dplyr) 
df1 %>% group_by(genre) %>% summarise(total_freq = sum(freq)) 
#  genre total_freq 
#1 Action   23 
#2 Adventure   12 
#3 Animation   1 
#4 Comedy   1 
#5  Crime   1 
#6 Family   1 
#7 Fantasy   1 

# where data df is 
#df 
#              Var1 Freq 
#1:             Action 11 
#2:          Action|Adventure 11 
#3: Action|Adventure|Animation|Comedy|Crime|Family|Fantasy 1 
+1

ありがとうございました!これは私が得たかったものです –

+0

は、実データ@Heheszekで効率的なソリューションでしたか?もしそれがあったら、答えをアップアップしてもいい?ありがとう。 http://stackoverflow.com/help/someone-answers –

+0

ああ、私はダニが十分だったと思いました。ご協力ありがとうございました。 –