R 如何同时为部分数据帧运行循环?

R 如何同时为部分数据帧运行循环?,r,dataframe,for-loop,subset,R,Dataframe,For Loop,Subset,这里有个新手!我有一个数据框,其中对于同一个ID有多个测量值。下面是一个简化的示例 id<-c(1,1,1,2,2,2,3,3,3) x<-as.numeric(c(1:9)) y<-c(2,4,1,5,7,3,9,6,8) z<-rep("text",9) cal<-0 df<- data.frame(id, x, y,z,cal) 因为我不想为每个ID创建数据帧的子集,所以我也尝试为ID使用for循环 for (i in 1:3) {if (df$id=

这里有个新手!我有一个数据框,其中对于同一个ID有多个测量值。下面是一个简化的示例

id<-c(1,1,1,2,2,2,3,3,3)
x<-as.numeric(c(1:9))
y<-c(2,4,1,5,7,3,9,6,8)
z<-rep("text",9)
cal<-0
df<- data.frame(id, x, y,z,cal)
因为我不想为每个ID创建数据帧的子集,所以我也尝试为ID使用for循环

for (i in 1:3)
{if (df$id==i) {
  for (j in 2:length(df$x))
  {if (df$x[j]>=df$y[j]) {df$cal[j]<-df$x[j]+df$y[j-1]
  }else{
     df$cal[j]<- df$x[j]-df$y[j-1]
    }
  }
}
} 
for(1:3中的i)
{if(df$id==i){
用于(2英寸j:长度(df$x))
{if(df$x[j]>=df$y[j]){df$cal[j]
您不需要循环。R是矢量化的。
lag()
创建一个向量,该向量被一个元素“移位”

现在还不清楚问题的第二部分是关于什么的,但你是不是在寻找这个

df %>%
    group_by(id) %>%
    mutate(cal = if_else(x >= y
                         , x + lag(y)
                         , x - lag(y)))

    id     x     y z       cal
<dbl> <dbl> <dbl> <fct> <dbl>
    1     1     1     2 text     NA
    2     1     2     4 text      0
    3     1     3     1 text      7
    4     2     4     5 text     NA
    5     2     5     7 text      0
    6     2     6     3 text     13
    7     3     7     9 text     NA
    8     3     8     6 text     17
    9     3     9     8 text     15
df%>%
分组依据(id)%>%
变异(cal=if_else(x>=y
,x+滞后(y)
,x-滞后(y)))
id x y z校准
1 1 2文本不适用
2 1 2 4文本0
3 1 3 1文本7
4 2 4 5文本不适用
5 2 5 7文本0
6 2 6 3文本13
7 3 7 9文本不适用
8 3 8 6文本17
9 3 9 8案文15

你能添加一个预期输出的样本吗?@NelsonGon我添加了我预期的数据帧类型。谢谢@Georgery!这看起来更为直截了当。如果我想在x>y时将x作为新的标定,并在x=y,x,lag(cal)时保留旧的标定,这是否也有效)
?我不完全确定你的意思,但在
mutate()
中,你也可以计算这个新版本。你也可以将它分配给另一个变量:
mutate(cal2=if_else(x>=y,x,lag(cal))
太好了,这就是我的意思。谢谢!
for (i in 1:3)
{if (df$id==i) {
  for (j in 2:length(df$x))
  {if (df$x[j]>=df$y[j]) {df$cal[j]<-df$x[j]+df$y[j-1]
  }else{
     df$cal[j]<- df$x[j]-df$y[j-1]
    }
  }
}
} 
library(tidyverse) # this loads several packages that will help you.

df %>% # now you take your df
    mutate(cal = if_else(x >= y # and calculate the column cal
                         , x + lag(y) # if x >= y then calculate this
                         , x - lag(y))) # else calculate this

  id x y    z cal
1  1 1 2 text  NA
2  1 2 4 text   0
3  1 3 1 text   7
4  2 4 5 text   3
5  2 5 7 text   0
6  2 6 3 text  13
7  3 7 9 text   4
8  3 8 6 text  17
9  3 9 8 text  15
df %>%
    group_by(id) %>%
    mutate(cal = if_else(x >= y
                         , x + lag(y)
                         , x - lag(y)))

    id     x     y z       cal
<dbl> <dbl> <dbl> <fct> <dbl>
    1     1     1     2 text     NA
    2     1     2     4 text      0
    3     1     3     1 text      7
    4     2     4     5 text     NA
    5     2     5     7 text      0
    6     2     6     3 text     13
    7     3     7     9 text     NA
    8     3     8     6 text     17
    9     3     9     8 text     15