我正在提供此示例数据以解决我的问题。

aid=c(1,2,3,4,5,6,7,8,9,10)
foson=c(0,1,2,0,6,9,0,0,3,0)
fosof=c(0,0,2,3,0,0,0,5,0,0)
data=data.frame(aid,foson,fosof)

现在,我需要使用以下条件创建一个名为 data$hist 的新变量(列):
if foson==0 and fosof==0, then hist = 0;
if foson >=1 and fosof==0, then hist = 1;
if foson==0 and fosof>=1, then hist = 2; and
if foson>=1 and fosof>=1, then hist = 3

我尝试使用“ifelse”功能但没有达到。

我希望这个问题足够清楚。

谢谢大家的帮助

巴松

最佳答案

Ramnath 的解决方案非常好,但要使用 ifelse 来实现,您可以这样做:

data$hist <- ifelse(data$foson>=1,ifelse(data$fosof>=1,3,1),ifelse(data$fosof>=1,2,0))

然而,这意味着如果 fosonfosof 中的任何一个是 <1 ,它将选择 ==0 的选项,但从您的数据来看,这似乎不是问题。

关于r - 当使用 R 满足某些条件时,使用两列创建一个新变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3632245/

10-15 18:39