我希望根據在另一個資料框的列中找到的唯一值的數量向資料框中添加未知數量的新列。我有以下兩個資料框:
| 用戶 | 文本字串 |
|---|---|
| 鮑勃 | 我喜歡黃色潛艇 |
| 簡 | 我喜歡紅車 |
my.base.df <- data.frame(
"user" = c("Bob", "Jane")
, "text.string" = c("I like yellow submarines", "I like red cars")
)
| 主題 | 學期 |
|---|---|
| 顏色 | 黃色 |
| 顏色 | 紅色的 |
| 顏色 | 藍色 |
| 汽車 | 福特 |
| 汽車 | 豐田 |
| 汽車 | 法幣 |
my.theme.df <- data.frame(
"theme" = c(rep("cars", 3), rep("colours", 3))
, "term" = c("ford", "toyota", "fiat", "red", "yellow", "blue")
)
我想標記在每個 text.string 中找到的主題,以這樣的方式結束:
| 用戶 | 文本字串 | 汽車 | 顏色 |
|---|---|---|---|
| 鮑勃 | 我喜歡黃色潛艇 | 0 | 1 |
| 簡 | 我喜歡紅車 | 1 | 1 |
我想我可以使用 for 回圈將術語與 text.string 匹配,但我擔心它在這個玩具示例之外無法擴展。但我真正堅持的一點是我無法my.base.df從結果動態創建“汽車”或“顏色”列levels(my.theme$themes)
在現實世界中,關卡的數量my.theme.df$theme可能多達 20 個,其中my.theme.df$term匹配一個my.theme.df$theme. 同樣,my.base.df最多可以包含一千個觀察值,所以我也擔心效率。
任何幫助或指示會很棒嗎?
謝謝,
杰米
uj5u.com熱心網友回復:
按主題拆分資料框,然后在相關字串上使用主題 所有相關術語。
my.base.df <- data.frame(
"user" = c("Bob", "Jane"),
"text.string" = c("I like yellow submarines", "I like red cars")
)
my.theme.df <- data.frame(
"theme" = c(rep("cars", 3), rep("colours", 3)),
"term" = c("ford", "toyota", "fiat", "red", "yellow", "blue")
)
theme_split <- split(my.theme.df, my.theme.df$theme)
for (x in names(theme_split)) {
# include theme itself in search
terms <- paste(c(theme_split[[x]][["term"]], x), collapse = "|")
my.base.df[[x]] <- grepl(terms, my.base.df$text.string)
}
my.base.df
#> user text.string cars colours
#> 1 Bob I like yellow submarines FALSE TRUE
#> 2 Jane I like red cars TRUE TRUE
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377738.html
標籤:r
