首页 / C# / 将C#转换为惯用的R
将C#转换为惯用的R
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将C#转换为惯用的R,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2594字,纯文字阅读大概需要4分钟。
内容图文
![将C#转换为惯用的R](/upload/InfoBanner/zyjiaocheng/756/9ff2121654aa4bb1a5f344d7ab721094.jpg)
最初,我正在使用我编写的一个简短的C#程序来平均一些数字.但是现在我想进行更广泛的分析,所以我将C#代码转换为R.但是,我真的不认为我在R中正确地使用它或利用语言.我用与C#完全相同的方式编写了R.
我有一个包含两列的CSV.第一列标识行的类型(三个值之一:C,E或P),第二列标识数字.我想平均分组在类型(C,E或P)上的数字.
我的问题是,在R中这样做的惯用方法是什么?
C#代码:
string path = "data.csv";
string[] lines = File.ReadAllLines(path);
int cntC = 0; int cntE = 0; int cntP = 0; //counts
double totC = 0; double totE = 0; double totP = 0; //totals
foreach (string line in lines)
{
String[] cells = line.Split(',');
if (cells[1] == "NA") continue; //skip missing data
if (cells[0] == "C")
{
totC += Convert.ToDouble(cells[1]);
cntC++;
}
else if (cells[0] == "E")
{
totE += Convert.ToDouble(cells[1]);
cntE++;
}
else if (cells[0] == "P")
{
totP += Convert.ToDouble(cells[1]);
cntP++;
}
}
Console.WriteLine("C found " + cntC + " times with a total of " + totC + " and an average of " + totC / cntC);
Console.WriteLine("E found " + cntE + " times with a total of " + totE + " and an average of " + totE / cntE);
Console.WriteLine("P found " + cntP + " times with a total of " + totP + " and an average of " + totP / cntP);
R代码:
dat = read.csv("data.csv", header = TRUE)
cntC = 0; cntE = 0; cntP = 0 # counts
totC = 0; totE = 0; totP = 0 # totals
for(i in 1:nrow(dat))
{
if(is.na(dat[i,2])) # missing data
next
if(dat[i,1] == "C"){
totC = totC + dat[i,2]
cntC = cntC + 1
}
if(dat[i,1] == "E"){
totE = totE + dat[i,2]
cntE = cntE + 1
}
if(dat[i,1] == "P"){
totP = totP + dat[i,2]
cntP = cntP + 1
}
}
sprintf("C found %d times with a total of %f and an average of %f", cntC, totC, (totC / cntC))
sprintf("E found %d times with a total of %f and an average of %f", cntE, totE, (totE / cntE))
sprintf("P found %d times with a total of %f and an average of %f", cntP, totP, (totP / cntP))
解决方法:
我会做这样的事情:
dat = dat[complete.cases(dat),] ## The R way to remove missing data
dat[,2] <- as.numeric(dat[,2]) ## convert to numeric as you do in c#
by(dat[,2],dat[,1],mean) ## compute the mean by group
当然要在data.frame中聚合你的结果你可以使用经典,但我不认为这里有必要,因为它是3个变量的列表:
do.call(rbind,result)
EDIT1
这里的另一个选择是使用优雅的大道:
ave(dat[,2],dat[,1])
但结果在这里有所不同.从某种意义上说,您将获得与原始数据长度相同的向量.
EDIT2要包含更多结果,您可以详细说明您的匿名函数:
by(dat[,2],dat[,1],function(x) c(min(x),max(x),mean(x),sd(x)))
或者返回data.frame更适合rbind调用和列名:
by(dat[,2],dat[,1],function(x)
data.frame(min=min(x),max=max(x),mean=mean(x),sd=sd(x)))
或者使用优雅的内置功能(您也可以定义)摘要:
by(dat[,2],dat[,1],summary)
内容总结
以上是互联网集市为您收集整理的将C#转换为惯用的R全部内容,希望文章能够帮你解决将C#转换为惯用的R所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。