Dirk Calloway
Dirk Calloway

Reputation: 2619

R Apply by row also sending last column as argument

I'm trying to apply a function to each row of a data frame and at the end of the results it is also printing the final column as well...

I'm not sure why this is the case.

df = data.frame(x = LETTERS[1:10], y = sample(1:5,10, replace = TRUE), z = sample(100:105, 10, replace = TRUE))

testprint = function (x){
  print(x[[1]])
  print(x[[2]])
  print(x[[3]])
}

apply(df, 1, testprint)

Result:

[1] "A"
[1] "2"
[1] "105"
[1] "B"
[1] "1"
[1] "103"
[1] "C"
[1] "5"
[1] "102"
[1] "D"
[1] "1"
[1] "101"
[1] "E"
[1] "3"
[1] "105"
[1] "F"
[1] "1"
[1] "100"
[1] "G"
[1] "3"
[1] "103"
[1] "H"
[1] "2"
[1] "101"
[1] "I"
[1] "3"
[1] "100"
[1] "J"
[1] "1"
[1] "100"
 [1] "105" "103" "102" "101" "105" "100" "103" "101" "100" "100"

Upvotes: 1

Views: 103

Answers (2)

user1981275
user1981275

Reputation: 13382

If you do not have use for the return value of apply, I don't see a reason to use apply at all. You do not seem to use the return value of print either, at least in your example. So why not use a for loop and cat?

for(i in seq_len(nrow(df)))cat(t(df)[,i], sep="\n")

Upvotes: 1

Roland
Roland

Reputation: 132999

From help("function"):

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

The last evaluated expression of your function is print(x[[3]]).

From help("print"):

print prints its argument and returns it invisibly (via invisible(x)).

And apply combines the return values in a vector, which is returned and printed (since you don't assign it).

Upvotes: 0

Related Questions