我有一個資料框 df1 是這樣的:
| 姓名 | 類別 |
|---|---|
| 蘋果 | 水果 |
| 香蕉 | 水果 |
| 卷心菜 | 蔬菜 |
| 蘋果 | 不適用 |
| 橙子 | 水果 |
| 卷心菜 | 不適用 |
| 玩具 | 雜項 |
| 蘋果 | 不適用 |
目前,資料框只有名稱第一次出現的類別。
但是,我想根據名稱填充資料框中的類別以使其像這樣:
| 姓名 | 類別 |
|---|---|
| 蘋果 | 水果 |
| 香蕉 | 水果 |
| 卷心菜 | 蔬菜 |
| 蘋果 | 水果 |
| 橙子 | 水果 |
| 卷心菜 | 蔬菜 |
| 玩具 | 雜項 |
| 蘋果 | 水果 |
將不勝感激!:)
uj5u.com熱心網友回復:
你可以使用dplyr::group_by然后tidyr::fill。
library(dplyr)
library(tidyr)
df1 %>%
group_by(Name) %>%
fill(Category) %>%
ungroup()
結果:
Name Category
<chr> <chr>
1 Apple Fruit
2 Banana Fruit
3 Cabbage Vegetable
4 Apple Fruit
5 Orange Fruit
6 Cabbage Vegetable
7 Toy Misc
8 Apple Fruit
資料:
df1 <- structure(list(Name = c("Apple", "Banana", "Cabbage", "Apple",
"Orange", "Cabbage", "Toy", "Apple"), Category = c("Fruit", "Fruit",
"Vegetable", NA, "Fruit", NA, "Misc", NA)), class = "data.frame", row.names = c(NA,
-8L))
uj5u.com熱心網友回復:
我們可以left_join從 dplyr 包中使用
library(dplyr)
dat %>%
left_join(dat %>%
drop_na() %>%
unique(), by = "Name") %>%
select(Name,
Category = Category.y)
Name Category
1 Apple Fruit
2 Banana Fruit
3 Cabbage Vegetable
4 Apple Fruit
5 Orange Fruit
6 Cabbage Vegetable
7 Toy Misc
8 Apple Fruit
%l%考慮使用qdapTools 包中的這種替代方法
library(qdapTools)
dat$Category <- dat[,1] %l% unique(dat[complete.cases(dat), ])
dat
Name Category
1 Apple Fruit
2 Banana Fruit
3 Cabbage Vegetable
4 Apple Fruit
5 Orange Fruit
6 Cabbage Vegetable
7 Toy Misc
8 Apple Fruit
我們也可以lookup從 qdapTools 包中使用
dat$Category <- lookup(dat[,1], unique(dat[complete.cases(dat), ]))
uj5u.com熱心網友回復:
在base R中,我們可以使用match(這非常類似于vlookup您熟悉的excel)
df1[,'Category'] = df1[,'Category'][match(df1$Name, df1$Name)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/522286.html
標籤:r
