如何从输出中获取某些值

时间:2015-10-20 12:55:51

标签: r

我有一个代码(代码的源代码在下面的链接中),它创建了以下输出:

target ~ birds
[1] 0.75
target ~ birds + wolfs
[1] 1

输出:

target ~ birds + wolfs
[1] 1 

是否有可能只获得超过特定值的结果?例如,在此输出中仅显示产生最佳精度值的模型公式,在这种情况下:

#include<stdio.h>
void main()
{
    printf("Hello world\n");
}

代码的来源来自链接:How to make an output txt file look better

1 个答案:

答案 0 :(得分:1)

您可以将结果存储在如下列表中:

df <- read.table(text = "target birds    wolfs     
                        0       21         7  
                        0        8         4  
                        1        2         5 
                        1        2         4 
                        0        8         3 
                        1        1         12  
                        1       7          10 
                        1        1         9 ",header = TRUE)
myform <-NULL
myform <- target~1
dd<-NULL
#I am initiating a list here
mylist <- list()
for ( i in c('birds', 'wolfs')) { 

  myform <- update(myform,  as.formula(paste('~ birds +', i)))
  glm<-glm(myform,data=dat)
  dat$glm_predict_response <- ifelse(predict(glm,newdata=dat,   type="response")>.5, 1, 0)
  sum1<- sum(dat$glm_predict_response>0 & dat$target>0)
  sum2<- sum(dat$glm_predict_response<1 & dat$target<1)
  accuracy<- (sum1+sum2)/length(dat$glm_predict_response)
  #I am adding each accuracy to the list
  #the name of each element of the list will be the formula(this is what deparse does here)
  #just as a side note: deparse does not work with very big formulas
  #you should use: Reduce(paste, deparse(myform))
  mylist[[deparse(myform)]] <- accuracy 

}

结果将是:

mylist
$`target ~ birds`
[1] 0.75

$`target ~ birds + wolfs`
[1] 1

既然你已经掌握了所有结果,那么你可以使用sink文本文件(如果你想要的话)sink('myfile.txt') print(mylist) sink()

#which.max chooses the max accuracy here
mylist[which.max(unlist(mylist))]
$`target ~ birds + wolfs`
[1] 1

然后你只能在屏幕上输出最佳模型:

sink('myfile.txt')
print(mylist[which.max(unlist(mylist))])
sink()

或者只是将最好的模型放到txt文件中:

function link_filter_offence($player_complaints_offence_raw)
        {
$player_complaints_offence_raw= 
preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $player_complaints_offence_raw);
$player_complaints_offence_raw= 
preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $player_complaints_offence_raw);
$player_complaints_offence_raw= 
preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $player_complaints_offence_raw);
            return($player_complaints_offence_raw);
        }

$player_complaints_offence_raw = 'https://www.youtube.com/watch?v=klXTQjmfVeg&feature=youtu.be';
$player_complaints_offence_raw = link_filter_offence($player_complaints_offence_raw);

$reply = html_entity_decode($player_complaints_offence_raw);
echo $reply;