head()函数在for循环中不起作用? [英] head() function does not work within 'for' loop?

查看:169
本文介绍了head()函数在for循环中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用for循环打印出几行。这里是代码。
奇怪的是它不适用于head()函数。如果我使用 print()替换 head(),它就可以工作了。

  kw_id = c('a','b')
keyword_text = data.frame(col = c('a','b'),col2 = c(1,2),row.names =(c('r1','r2')))

for(i in 1:2){
plot_data< -subset keyword_text,col == kw_id [i])
print(plot_data)
head(plot_data)
}

有人可以帮忙吗?我怀疑它与 head()函数有关。

解决方案

这是一个相当普遍的问题类型的R进入到新来者。这里的问题是,R为两位情妇提供服务:交互式控制台工作和真正的编程。

在控制台输入一个返回值的命令时, em>自动调用打印方法以显示结果。所以如果你把它改成 print(head(plot_data)),就不会发生这种情况。



常见问题 7.16 7.22



附录从评论中解除:

正如Josh指出的那样,将for循环直接复制粘贴到控制台也无法打印任何输出。在这种情况下发生的事情是,循环(就像R中的大部分内容)实际上是一个函数,它的返回值( NULL )被隐式返回,这意味着不打印。 (这在?Control 中提到。)


I tried using a for loop to print out a few rows. here is the code. Weird thing is that it doesn't work for head() function. It works if I replaced head() with print().

kw_id=c('a','b')
keyword_text=data.frame(col=c('a','b'), col2=c(1,2), row.names=(c('r1','r2')))

for (i in 1:2) { 
   plot_data<-subset(keyword_text,col==kw_id[i])
   print(plot_data)
   head(plot_data)
}

Could someone help? I suspect it has something to do with head() function.

解决方案

This is a relatively common class of problem that newcomers to R run into. The issue here is that R serves two mistresses: interactive console work and "true programming".

When you type a command at the console that returns a value, the console automatically calls a print method in order to display the results. When running a script, this doesn't happen unless you tell it to.

So if you changed it to print(head(plot_data)) it should work.

These are discussed in FAQ 7.16 and 7.22

Addendum lifted from the comments:

As Josh points out, copy+pasting the for loop directly to the console also fails to print any output. What's going on in that case is that for loops (like most everything in R) is actually a function, and it's return value (NULL) is returned invisibly, which means no printing. (This is mentioned in ?Control.)

这篇关于head()函数在for循环中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆