head() function does not work within 'for' loop?

前端 未结 1 345
太阳男子
太阳男子 2021-01-21 19:49

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

相关标签:
1条回答
  • 2021-01-21 20:14

    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.)

    0 讨论(0)
提交回复
热议问题