是否有基于其他值的简单方式将值添加到数据框?

时间:2018-08-16 11:00:32

标签: r

我有一个零售商代码列表。

我希望根据零售商代码将零售商名称/国家/地区添加到retailer列中,以便查看结果的人员能够了解他们与哪个零售商相关。

目前,我有这个:

chats$retailer[chats$retailer_code == "npqPjZyMy5"] <- "France"
chats$retailer[chats$retailer_code == "HbNaIqdedB"] <- "Germany"
chats$retailer[chats$retailer_code == "p7VtqCMCr8"] <- "Italy"
chats$retailer[chats$retailer_code == "Tj8vwJvyH1"] <- "Japan"
chats$retailer[chats$retailer_code == "1mRdYODJBH"] <- "UAE"
chats$retailer[chats$retailer_code == "GGdwO3HFDV"] <- "UK"

chats$retailer_code <- NULL # Remove retailer code column

是否有更简洁的方法来实现这一目标?

4 个答案:

答案 0 :(得分:0)

这将节省您的一些时间。

library(plyr)
chats$retailer <- revalue(chats$retailer,
                                  c("npqPjZyMy5" = "France", "HbNaIqdedB" = "Germany", "p7VtqCMCr8" = "Italy", "Tj8vwJvyH1" = "Japan","1mRdYODJBH" = "UAE","GGdwO3HFDV" = "UK" ))

答案 1 :(得分:0)

library(tidyverse)
chats%>%
  mutate(retailer = case_when(
    retailer_code=="npqPjZyMy5"~"France",
    retailer_code=="HbNaIqdedB"~"Germany",
    retailer_code=="p7VtqCMCr8"~"Italy",
    retailer_code=="Tj8vwJvyH1"~"Japan",
    retailer_code=="1mRdYODJBH"~"UAE",
    retailer_code=="GGdwO3HFDV"~"UK"))%>%
  select(-retailer_code)

答案 2 :(得分:0)

或带有查找向量:

static final _textKey = GlobalKey<FormState>();

答案 3 :(得分:0)

我将提供一个基本的R解决方案,以供参考。

# Example data
chats <- data.frame(
  other_column = 1:6,
  retailer_code = c("npqPjZyMy5", "HbNaIqdedB", "p7VtqCMCr8", "Tj8vwJvyH1", "1mRdYODJBH", "GGdwO3HFDV")
)

# Example key
retailer_key <- data.frame(
  retailer_code = c("npqPjZyMy5", "HbNaIqdedB", "p7VtqCMCr8", "Tj8vwJvyH1", "1mRdYODJBH", "GGdwO3HFDV"),
  retailer = c("France", "Germany", "Italy", "Japan", "UAE", "UK")
)

# Example join using base::merge
merge(chats, retailer_key)