0

I have a dataframe with 12665x784 dimension and I need to call a function over each row (this function expects an input of 1x784 from the dataframe and a constant with the same size) and store the result in another vector. The code using for loop is shown bellow:

sample <- 1:20
my.constant <- 1:5
dim(sample) <- c(4, 5)
df <- as.data.frame(sample)

my.function <- function (x, y){
  y <- as.matrix(y)
  x <- as.matrix(x)
  return(x%*%y)
}

result <- c()

for (row in 1:nrow(df)) {
  result<- c(result, my.function(df[row, ], my.constant))
}

I've tried the following approach, but it didn't work:

result <- sapply(lapply(df, as.vector), my.function, my.constant)
  • 4
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Apr 09 '18 at 14:10
  • you can `?apply` – Andre Elrico Apr 09 '18 at 14:24
  • @Jaap, I edited the question to provide a reproducible example. Sorry about that. – Kennedy Sousa Apr 09 '18 at 14:26
  • `as.matrix(df) %*% my.constant` or `c(as.matrix(df) %*% my.constant)` – jogo Apr 09 '18 at 14:29

2 Answers2

0
  1. Is your function a matrix product?

  2. Is your data only numeric values?

Then you just want a matrix product between a matrix and a vector:

as.matrix(df) %*% my.constant

with possibly using drop() if you want a vector instead of a one-column matrix.

F. Privé
  • 11,423
  • 2
  • 27
  • 78
  • 1. Actually, my function is more complex much more complex than that. I used a dot product to make it simple. 2. All data is only numeric values. – Kennedy Sousa Apr 09 '18 at 16:56
  • Okay. Can you use a more complex function? I'll edit my answer with these new information. – F. Privé Apr 09 '18 at 17:10
-1

See if this helps...

id<-c("A", "B", "C")
v1<-c(10, 4, 9)
df<-data.frame(id, v1)


result<-unlist(lapply(df$v1, function(x){
  x+1
}))

result
Alex S
  • 21
  • 4
  • Why would you mark down my answer? I gave you a reproducible example of how to apply any function you create to all records and then collect them in a vector as you asked. Your functions makes no sense... you need to fix that first. You created one data frame but have two inputs for your function... – Alex S Apr 09 '18 at 18:02
  • In your case `unlist(lapply(...))` is identical with `sapply(...)`. In the mean time there is a reproducible example in the question. – jogo Apr 10 '18 at 08:34