简体   繁体   中英

Using lapply to apply function to each row in a tibble

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM