この質問のフォローアップとして、反対のタスクaggregate
(またはdata.table
以下のMWEと同等のタスク)を実行して、df2から開始してdf1を再度取得したいと思います。
ここでのタスクは、df2からdf1を再現することです。このために試しましたがtidytext::unnest_tokens
、複数の変数を「分解」する必要がある場合(モデル、国、年)、正しく機能させる方法がわかりません。
変数の元の大文字も保持しておくと便利です。
とは異なるエレガントなソリューションtidytext::unnest_tokens
が受け入れられます!ありがとう!
これがMWEです。
####MWE
library(data.table)
library(tidytext)
df1 <- data.frame(brand=c(rep('A',4), rep('B',5), rep('C',3), rep('D',2),'E'),
model=c('A1','A1','A2','A3','B1','B2','B2','B2','B3','C1','C1','C2','D1','D2','E1'),
country=c('P','G','S','S','P','P','F','I','D','S','F','F','G','I','S'),
year=c(91,92,93,94,98,95,87,99,00,86,92,92,93,95,99))
df1
dd <- data.table(df1)
df2 <- as.data.frame(dd[, list(models=paste(model, collapse=' /// '),
countries=paste(country, collapse=' /// '),
years=paste(year, collapse=' /// ')),
by=list(brand=brand)])
df2
df1b <- df2 %>%
unnest_tokens(model, models, token = "regex", pattern = " /// ")
df1b
####
使用できます separate_rows
library(tidyverse)
res <- df2 %>%
separate_rows(models, countries, years, convert = TRUE) %>%
rename_all(funs(paste0(names(df1)))) %>% #just to make the column names same as df1
mutate(year = as.numeric(year)) #convert to numeric to match df1 column type
all.equal(res, df1 %>%
mutate_at(2:3, as.character), check.attributes = FALSE )
#[1] TRUE
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加