euromail1
euromail1

Reputation: 1

Apply a function to specific columns with variable arguments

I have the following matrix, we can call it MM,

I want to put it in a datatable, but I want to apply a function to column 3, 4 and 5 and by Student_ID which means for

Student_ID = 1

I want to take three separate vector :

MM[1:3,3] , MM[1:3,4], MM[1:3,5]

and apply a function which takes as an input each vector, and two vectors

aa=c(10,20,30) and bb=c(100,200,300)

for instance we can assume that my function returns aa[j]*x+bb[j] and returns the sum of this.

Could you please help me?

MM <- structure(c(1, 1, 1, 2, 2, 2, 2, 2, 1, 2, 3, 1, 2, 3, 4, 5, 1554932, 
5477822, 7086366, 9944580, 4462829, 211916, 3082177, 8411017, 
5006119, 8958476, 644312, 806333, 177816, 6066293, 6941193, 8687443, 
2707671, 6593003, 4005567, 4501512, 4127272, 9329248, 4284849, 
7621552), dim = c(8L, 5L), dimnames = list(NULL, c("Student_ID", 
"#_of_exams", "#_of_points_Lesson_1", "#_of_points_Lesson_2", 
"#_of_points_Lesson_3")))
  [Student_ID] [#_of_exams]    [#_of_points_Lesson_1]    [#_of_points_Lesson_2]    [#_of_points_Lesson_3]
 [1,]    1    1 1554932 5006119 2707671
 [2,]    1    2 5477822 8958476 6593003
 [3,]    1    3 7086366  644312 4005567
 [4,]    2    1 9944580  806333 4501512
 [5,]    2    2 4462829  177816 4127272
 [6,]    2    3  211916 6066293 9329248
 [7,]    2    4 3082177 6941193 4284849
 [8,]    2    5 8411017 8687443 7621552

Upvotes: 0

Views: 50

Answers (1)

Eonema
Eonema

Reputation: 1320

If you're okay with using a data frame instead of a data table, you can use summarize(across()) from dplyr:

as.data.frame(MM[1:3,]) %>% 
  summarise(across(
    starts_with("#_of_points_Lesson_"),
    ~sum(aa*.x+bb) # your function
  ))

Or, if your function needs more than one line:

# your function:
fn <- function(x) {
  sum(aa*x+bb)
}

as.data.frame(MM[1:3,]) %>% 
  summarise(across(starts_with("#_of_points_Lesson_"), fn))

Upvotes: 0

Related Questions