如果为R的其他功能

时间:2018-10-01 12:42:24

标签: r if-statement

我的数据框如下:

'data.frame':   7 obs. of  3 variables:
 $ Currency : Factor w/ 3 levels "EUR","GBP","USD": 3 3 1 2 3 1 2
 $ Amount.LC: int  100 500 400 200 350 100 500
 $ FX.Rate  : Factor w/ 3 levels "0,89","1,201",..: 2 2 3 1 2 3 1

基于“ if-else”函数,我尝试计算一个新列,称为Amount.GC,这取决于“ EUR”是否在Currency列中。如果“ EUR”比我想要的值与Amount.LC列中的值相同。否则我想将Amount.LC和FX.Rate(Amount.LC/FX.Rate)分开。

我的代码如下:

for (i in df$Currency){if (i == "EUR"){df$Amount.GC <- df$Amount.LC}
else{df$Amount.GC <- c(df$Amount.LC)/c(df$FX.Rate)}}

不幸的是,它不起作用。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

如评论中所述,您不需要forloop。您可以在ifelse条件下进行所有操作,然后将结果直接分配给新列。

df = data.frame(
  Currency = sample(c("EUR", "GBP", "USD"), size = 10, replace = T),
  Amount.LC = sample(c(100,200,300,400,500), size=10, replace = T),
  FX.Rate = sample(c(0.89, 1.201, 1,5), size=10, replace=T)
)


df$Amount.GC = ifelse(df$Currency == "EUR", df$Amount.LC, (df$Amount.LC/df$FX.Rate))

df