使用 dplyr 更改观察的名称

Changing observation`s name using dplyr

假设我有这个数据集:

Variable <- c("GDP")
Country <- c("Brazil", "Chile") 
df <- data.frame(Variable, Country)

我想将 GDP 更改为 "Country_observation" GDP,即巴西 GDP 和智利 GDP。

我有一个更大的数据集,我一直在尝试使用

来做到这一点
df %>% mutate(Variable = replace(Variable, Variable == "GDP", paste(Country, "GDP")))

但是,它会为 "Variable" 中满足条件的每个观察打印变量 "Country" 的第一个观察。有什么方法可以让 paste() 在它所应用的行上使用 Country 的值吗?

我试过使用 rowwise() 但它不起作用。我也试过下面的代码,遇到了同样的问题

df %>% mutate(Country = ifelse(Country == "Chile", replace(Variable, Variable == "GDP", 
paste(Country, "GDP")), Variable))

谢谢大家!

编辑

我不能简单地使用 unite,因为我仍然需要变量 Country。所以我找到的一个解决方法是(我有几个其他观察结果需要更改它们的名称)

df %>% mutate(Variable2 = ifelse(Variable == "GDP", paste0(Country, " ",
Variable), Variable)) %>% 
mutate(Variable2 = replace(Variable2, Variable2 ==
"CR", "Country Risk")) %>% 
mutate(Variable2 = replace(Variable2, Variable2 
== "EXR", "Exchange Rate")) %>% 
mutate(Variable2 = replace(Variable2,mVariable2 == "INTR", "Interest Rate")) 
%>% select(-Variable) %>% 
select(Horizon, Variable = Variable2, Response, Low, Up, Shock, Country,
Status)

编辑 2 我想要的输出是

Horizon   Variable   Response Shock Country
1         Brazil GDP   0.0037  PCOM  Brazil
2         Brazil GDP   0.0060  PCOM  Brazil
3         Brazil GDP   0.0053  PCOM  Brazil
4         Brazil GDP   0.0033  PCOM  Brazil
5         Brazil GDP   0.0021  PCOM  Brazil
6         Brazil GDP   0.0020  PCOM  Brazil

这个例子应该有帮助:

library(tidyr)
library(dplyr)

Variable <- c("GDP")
Country <- c("Brazil", "Chile") 
value = c(5,10)
df <- data.frame(Variable, Country, value)

# original data
df

#   Variable Country value
# 1      GDP  Brazil     5
# 2      GDP   Chile    10

# update
df %>% unite(NewGDP, Variable, Country)

#       NewGDP value
# 1 GDP_Brazil     5
# 2  GDP_Chile    10

如果你想使用 paste 你可以这样做:

df %>% mutate(NewGDP = paste0(Country,"_",Variable))

#   Variable Country value     NewGDP
# 1      GDP  Brazil     5 Brazil_GDP
# 2      GDP   Chile    10  Chile_GDP