![](/img/trans.png)
[英]If two columns have the same value, how can I replace NA in a third column with this value in R?
[英]How can I replace an NA value in a column for something if I have an specific value in another column?
使用 tidyr 我想修改一個 dataframe。基本上在這個 dataframe 中,我有一個包含不同類型產品的列:水果、蔬菜、肉類等……我們稱它為“組”列。
在同一個 dataframe 中,我還有一個包含產品 label 的列:水果和蔬菜產品、農產品、新鮮產品……我們稱之為“標簽”列。
我要做的是根據 Label 列的結果替換 Group 列的 NA 值。 例如:如果 Label 列顯示“農產品”,那么我想用值“牛奶”替換組列的 NA 值。 如果 Label 列顯示“Fruits and Vegetables products”,我希望 Group 列的 NA 值取值“Vegetables”。
為此,我一直在嘗試使用以下代碼:
data_ES$Group <- data_ES$Group %>%
replace_na('Vegetables', if(data_ES$Label = "Fruits and Vegetables products"))
當然這是行不通的,因為這只是我的直覺,我是編程新手。
有人可以給我提示或想法嗎?
我編寫了一個小例子,因為我猜你正在尋找什么:
library(tidyverse)
df <- tibble(Group = c(NA,"Fruits","Vegetables",NA,"Meat"),
Label = c("Fruits and Vegetables products",
"Fruits and Vegetables products",
"Fruits and Vegetables products",
"Farm products","Farm products" ))
df_replaced <- df %>% mutate(Group = case_when(Label == "Fruits and Vegetables products" & is.na(Group)
~ "Vegetables",
Label == "Farm products" & is.na(Group) ~ "Milk",
TRUE ~ Group))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.