假设我有这个数据集:
Variable <- c("GDP")
Country <- c("Brazil", "Chile")
df <- data.frame(Variable, Country)
我想将GDP改为“国家观察”GDP,即巴西GDP和智利GDP。
我有一个更大的数据集,我一直试图通过使用
来做到这一点df %>% mutate(Variable = replace(Variable, Variable == "GDP", paste(Country, "GDP")))
然而,它将为符合条件的“变量”中的每个观察打印变量“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
答案 0 :(得分:3)
这个例子应该有所帮助:
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