创建循环函数,用于从 R 中的另一列计算一列的值
对于数据框 AB:
AB<-data.frame(ID=c(1,2,4),A=c(2,8,8),B=c(6,2,2),dE=c(0,0,0))
我想应用以下公式:AB$dE=AB$B/AB$A
ID A B dE
1 2 6 0
2 8 2 0
4 8 2 0
将以上内容转换为:
ID A B dE
1 2 6 3
2 8 2 0.25
4 8 2 4
因为我有几个文件包含不同的列名称A和B,编写一个函数会更实用,这样
dEs <- function(data,nume,denom){
#define which datafile and numerator/denom column
#so in case of AB this becomes AB$dE;
# i dont know the correct way to do this.
dE=data.'$dE'
start=data.'$'.nume #to become AB$A
end=data.'$'.denom #to become AB$B
for(i in data){
dE[i] <- (start[i]/end[i])
}
}
我就可以在必要时更改分子/分母。
For on the dataframe AB:
AB<-data.frame(ID=c(1,2,4),A=c(2,8,8),B=c(6,2,2),dE=c(0,0,0))
I would like to apply the following formula: AB$dE=AB$B/AB$A
ID A B dE
1 2 6 0
2 8 2 0
4 8 2 0
to convert the above to:
ID A B dE
1 2 6 3
2 8 2 0.25
4 8 2 4
because I have several files that contain different column names for A and B, it would be more practical to write a function, something like
dEs <- function(data,nume,denom){
#define which datafile and numerator/denom column
#so in case of AB this becomes AB$dE;
# i dont know the correct way to do this.
dE=data.'$dE'
start=data.'
this way I would be able to change the numerator/denominator when necessary.
.nume #to become AB$A
end=data.'
this way I would be able to change the numerator/denominator when necessary.
.denom #to become AB$B
for(i in data){
dE[i] <- (start[i]/end[i])
}
}
this way I would be able to change the numerator/denominator when necessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不需要循环,因为 R 是矢量化的:
如果你真的想要一个函数,你可以使用
[[]]
来选择列,因为 data.frame 只是一个列表(假设 num和 denom 是带有所需列名称的字符向量):You don't need a loop, since R is vectorized:
If you really want a function, you can use
[[]]
to select columns, since a data.frame is just a list (assuming nume and denom are character vectors with the name of the column you want):