R 在循环中沿列移动
我正在尝试使用以下数据创建此函数:R 在循环中沿列移动,r,for-loop,R,For Loop,我正在尝试使用以下数据创建此函数: df<-read.table(text="x y 0 1000 0 1000 4 1000 2 1000 10 1000 5 1000",header=T) 我希望第二列显示0。以下是您可以进行的一些更改。以下是完整的功能: rowdiff<-function(df,na.rm=F){ > mrowdiff <- df # you want mrowdiff to have the same b
df<-read.table(text="x y
0 1000
0 1000
4 1000
2 1000
10 1000
5 1000",header=T)
我希望第二列显示0。以下是您可以进行的一些更改。以下是完整的功能:
rowdiff<-function(df,na.rm=F){
> mrowdiff <- df # you want mrowdiff to have the same basic structure as df, so start with making it equal to df (there are more efficient ways to do this)
> for(i in 1:nrow(df))
+ {
+ mrowdiff[i, ]<-df[i+1, ]-df[i, ] # calculate differences for both rows at once
+ }
> mrowdiff<- na.omit(mrowdiff) # remove missing values
> mrowdiff # there's nothing to rbind, since you've been working with a dataframe all along
}
rowdiff(df)
x y
1 0 0
2 4 0
3 -2 0
4 8 0
5 -5 0
rowdiff mrowdiff for(1中的i:nrow(df))
+ {
+mrowdiff[i,]mrowdiff mrowdiff#没有什么好发现的,因为您一直在使用数据帧
}
rowdiff(df)
xy
1 0 0
2 4 0
3 -2 0
4 8 0
5 -5 0
以下是您可以进行的一些更改。以下是完整的功能:
rowdiff<-function(df,na.rm=F){
> mrowdiff <- df # you want mrowdiff to have the same basic structure as df, so start with making it equal to df (there are more efficient ways to do this)
> for(i in 1:nrow(df))
+ {
+ mrowdiff[i, ]<-df[i+1, ]-df[i, ] # calculate differences for both rows at once
+ }
> mrowdiff<- na.omit(mrowdiff) # remove missing values
> mrowdiff # there's nothing to rbind, since you've been working with a dataframe all along
}
rowdiff(df)
x y
1 0 0
2 4 0
3 -2 0
4 8 0
5 -5 0
rowdiff mrowdiff for(1中的i:nrow(df))
+ {
+mrowdiff[i,]mrowdiff mrowdiff#没有什么好发现的,因为您一直在使用数据帧
}
rowdiff(df)
xy
1 0 0
2 4 0
3 -2 0
4 8 0
5 -5 0
这是一种避免使用函数的简单方法,尽管您提到
for (j in 1:ncol(df)) {
df[,paste0("rowdiff",j)] <- NA
for (i in 2:nrow(df)) {
df[i,paste0("rowdiff",j)] <- df[i,j] - df[i-1,j]
}
}
这是一种避免使用函数的简单方法,尽管您提到
for (j in 1:ncol(df)) {
df[,paste0("rowdiff",j)] <- NA
for (i in 2:nrow(df)) {
df[i,paste0("rowdiff",j)] <- df[i,j] - df[i-1,j]
}
}
我可能误解了您的最终目标(这有点不清楚),但是您考虑过<代码>差异(<)>代码>函数吗?您可能需要在大于行数<代码> i+1 的情况下考虑该情况。我正在为学习目的编写我自己的函数。因此,我避免使用基于基本或包的解决方案。我们的目标是获得“累积差异”。这个例子的预期输出是什么?@JosephClarkMcIntyre补充道。我可能误解了您的最终目标(有点不清楚),但您是否考虑了
diff()当它大于行数<代码> i+1 时,您可能需要考虑该情况。我正在为学习目的编写我自己的函数。因此,我避免使用基于基本或包的解决方案。我们的目标是获得“累积差异”。这个例子的预期输出是什么?@JosephClarkMcIntyre补充道。这似乎不起作用,或者我误解了它。你能发布完整的功能吗?我添加了完整的功能,从一个干净的工作区开始。你觉得怎么样?也许我误解了这个问题?你建议的编辑很好,但我不完全确定如何使它们生效,所以我手工制作。不用担心。再次感谢。这似乎不起作用,或者我误解了。你能发布完整的功能吗?我添加了完整的功能,从一个干净的工作区开始。你觉得怎么样?也许我误解了这个问题?你建议的编辑很好,但我不完全确定如何使它们生效,所以我手工制作。不用担心。再次感谢。
> df
x y rowdiff1 rowdiff2
1 0 1000 NA NA
2 0 1000 0 0
3 4 1000 4 0
4 2 1000 -2 0
5 10 1000 8 0
6 5 1000 -5 0