我目前有一個.csv資料檔案,內容如下:
Name Fruit Qty
Tauwen Apple 32
Tauewn Pear 09
Wikfae Apple 09
Moigaw Pear 16
我想使用 R 為“Wikfae”插入缺失的“Pear”,相應的數量為 0,為“Moigaw”插入缺失的“Apple”,相應的數量為 0。所以我想要的輸出表是:
Name Fruit Qty
Tauwen Apple 32
Tauewn Pear 09
Wikfae Apple 09
Wikfae Peak 0 #Added line
Moigaw Pear 16
Moigaw Apple 0 #Added line
我什至不知道從哪里開始。基于Atidyverse的解決方案對我來說最有用。
uj5u.com熱心網友回復:
我們可以使用complete:
library(tidyr)
df |>
complete(Name, Fruit, fill = list(Qty = "0"))
輸出:
# A tibble: 6 × 3
Name Fruit Qty
<chr> <chr> <chr>
1 Moigaw Apple 0
2 Moigaw Pear 16
3 Tauwen Apple 32
4 Tauwen Pear 09
5 Wikfae Apple 09
6 Wikfae Pear 0
但是,您可能會考慮轉換Qty為數字:
df |>
mutate(Qty = as.numeric(Qty)) |>
complete(Name, Fruit, fill = list(Qty = 0))
輸出:
# A tibble: 6 × 3
Name Fruit Qty
<chr> <chr> <dbl>
1 Moigaw Apple 0
2 Moigaw Pear 16
3 Tauwen Apple 32
4 Tauwen Pear 9
5 Wikfae Apple 9
6 Wikfae Pear 0
無錯別字的資料:
library(readr)
df <-
read_table("Name Fruit Qty
Tauwen Apple 32
Tauwen Pear 09
Wikfae Apple 09
Moigaw Pear 16")
uj5u.com熱心網友回復:
我不確定我是否正確理解了你的問題,但從它的聲音來看,你想要通過外科手術將行添加到你的資料中。這可以簡單地使用add_row. 首先我模擬了你的資料:
#### Simulate Data ####
Name <- c("Tauwen","Tauwen","Wikfae","Moigaw")
Fruit <- c("Apple","Pear","Apple","Pear")
Qty <- c(32,09,09,16)
tib <- tibble(
Name,
Fruit,
Qty
)
然后我添加了行,首先通過一個特定的位置(.before這里說在哪一行之前放置它),然后在最后添加一行。
#### Add Rows ####
tib %>%
add_row(Name = "Wikfae",
Fruit = "Peak",
Qty = 0,
.before = 4) %>%
add_row(Name = "Moigaw",
Fruit = "Apple",
Qty = 0)
給你這個:
# A tibble: 6 × 3
Name Fruit Qty
<chr> <chr> <dbl>
1 Tauwen Apple 32
2 Tauwen Pear 9
3 Wikfae Apple 9
4 Wikfae Peak 0
5 Moigaw Pear 16
6 Moigaw Apple 0
如果您的目標只是在資料框中完成觀察,這些值已經以某種方式存在,那么 Harre 在這里的另一個答案可能是更好的選擇。
uj5u.com熱心網友回復:
這是@harre 的首選答案的漫長方法:
library(dplyr)
library(tidyr)
df %>%
group_by(Name) %>%
summarise(cur_data()[seq(2),]) %>%
ungroup() %>%
mutate(Fruit = if(first(Fruit) == "Pear") replace(Fruit, is.na(Fruit), "Apple")
else replace(Fruit), is.na(Fruit), first(Fruit)) %>%
mutate(Qty = replace_na(Qty, 0)) %>%
select(Name, Fruit, Qty)
Name Fruit Qty
<chr> <chr> <int>
1 Moigaw Pear 16
2 Moigaw Apple 0
3 Tauwen Apple 32
4 Tauwen Pear 9
5 Wikfae Apple 9
6 Wikfae Apple 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534804.html
標籤:r整洁的
