使用 if-else if-else 语句在 R 中生成附加变量

时间:2021-03-09 14:35:57

标签: r dataframe if-statement

我想向以 a 为条件的数据框 b 添加两个新变量 mid。我该怎么做?

m <- data.frame(id=c(1,1,2,2,3,3),
                v1=c(1,2,2,3,3,5),
                v2=c(6,7,8,9,4,5))
if(m$id==1){
  m$a <- m$v1*m$v2
  m$b <- m$v1/m$v2
} else if(m$id==2){
  m$a <- m$v1-m$v2
  m$b <- m$v1+m$v2
} else
  m$a <- m$v1
  m$b <- m$v2

我收到一条错误消息,显示 the condition has length > 1 and only the first element will be used。任何帮助表示赞赏!

0 个答案:

没有答案