Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lapply to apply function to each row in a tibble

Tags:

r

This is my code that attempts apply a function to each row in a tibble , mytib :

> mytib
# A tibble: 3 x 1
  value
  <chr>
1     1
2     2
3     3

Here is my code where I'm attempting to apply a function to each line in the tibble :

mytib = as_tibble(c("1" , "2" ,"3"))

procLine <- function(f) {
  print('here')
  print(f)
}

lapply(mytib , procLine)

Using lapply :

> lapply(mytib , procLine)
[1] "here"
[1] "1" "2" "3"
$value
[1] "1" "2" "3"

This output suggests the function is not invoked once per line as I expect the output to be :

here
1
here
2
here
3

How to apply function to each row in tibble ?

Update : I appreciate the supplied answers that allow my expected result but what have I done incorrectly with my implementation ? lapply should apply a function to each element ?

like image 455
blue-sky Avatar asked Nov 06 '17 22:11

blue-sky


People also ask

How do I apply a function to each row of a Dataframe in R?

You can use the apply() function to apply a function to each row in a matrix or data frame in R.

What does the Lapply () function in R is used for?

The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.

Can you use Lapply on a Dataframe in R?

In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply.

Can you use Lapply on a Dataframe?

lapply() on a data frame. If, instead of a list, you had a data frame of stock returns, could you still use lapply() ? Yes! Perhaps surprisingly, data frames are actually lists under the hood, and an lapply() call would apply the function to each column of the data frame.


1 Answers

invisible is used to avoid displaying the output. Also you have to loop through elements of the column named 'value', instead of the column as a whole.

invisible( lapply(mytib$value , procLine) )
# [1] "here"
# [1] "1"
# [1] "here"
# [1] "2"
# [1] "here"
# [1] "3"

lapply loops through columns of a data frame by default. See the example below. The values of two columns are printed as a whole in each iteration.

mydf <- data.frame(a = letters[1:3], b = 1:3, stringsAsFactors = FALSE )
invisible(lapply( mydf, print))
# [1] "a" "b" "c"
# [1] 1 2 3

To iterate through each element of a column in a data frame, you have to loop twice like below.

invisible(lapply( mydf, function(x) lapply(x, print)))
# [1] "a"
# [1] "b"
# [1] "c"
# [1] 1
# [1] 2
# [1] 3
like image 59
Sathish Avatar answered Nov 15 '22 04:11

Sathish