我的数据框如下所示:
var1 var2 var3
1 0 5 "other"
2 25 3 "sample"
3 4 5 "other"
4 60 5 "other"
5 4 5 "other"
6 60 5 "other"
7 25 3 "sample"
8 4 8 "other"
9 60 7 "other"
10 4 3 "other"
11 25 27 "sample"
12 4 9 "other"
13 30 4 "other"
我想添加一列,对于等于var3 = =“sample”的所有行,我们计算var2列中的值减去“sample”行下面的行的var 2列中的值。这看起来像这样:
var1 var2 var3 var4
1 0 5 "other" NA
2 25 25 "sample" 20
3 4 5 "other" NA
4 60 5 "other" NA
5 4 5 "other" NA
6 60 5 "other" NA
7 25 13 "sample" 8
8 4 5 "other" NA
9 60 5 "other" NA
10 4 3 "other" NA
11 25 27 "sample" 18
12 4 9 "other" NA
13 30 4 "other" NA
我试过了
if(df$var3=="sample") {df$var4<-(df$var2-df$var2[+1,])}
但这显然不起作用。如何使用特定行中的列及其下方的确切行进行计算?
答案 0 :(得分:2)
我们可以减去def delete_projection():
with open('projections.txt') as projections:
#projections = open('users.txt', 'r').readlines()
delete = input("Input projection code you want to delete: ")
for i in projections:
projection = i.strip("\n").split("|")
if delete == projection[0]:
projection[8]="false"
#projections.close()
with open('projections.txt', 'w+') as projections:
projections.write("false")
projections.close()
,即&#39; var2&#39;的下一个元素。当&#39; var3&#39;是&#39;样本&#39;
lead
library(dplyr)
df1 %>%
mutate(var4 = ifelse(var3 == "sample", var2 -lead(var2), NA))