yasel
yasel

Reputation: 453

Passing dataframe as argument to function

I am writing a function to process data from a huge dataframe (row by row) which always has the same column names. So I want to pass the dataframe itself as a function to read out the information I need from the individual rows. However, when I try to use it as argument I can't read the information from it for some reason.

Dataframe:

DF <- data.frame("Name" = c("A","B"), "SN" = 1:2, "Age" = c("21,34,456,567,23,123,34", "15,345,567,3,23,45,67,76,34,34,55,67,78,3"))

My code:

List <- do.call(list, Map(function(DT) {
  DT <- as.data.frame(DT)
  aa <- as.numeric(strsplit(DT$Age, ","))
  mean.aa <- mean(aa)
},
DF))

Trying this I get a list with the column names, but all Values are NULL.

Expected output : My expected output is a list with length equal to the number of rows in the data frame. Under each list index there should be another list with the age of the corresponding row (an also other stuff from the same row of the data table, later).

DF <- apply(data.frame("Name" = c("A","B"), "SN" = 1:2, "Age" = c("21,34,456,567,23,123,34", "15,345,567,3,23,45,67,76,34,34,55,67,78,3"), "mean.aa" = c(179.7143, 100.8571)), 1, as.list)

What am I doing wrong?

Upvotes: 1

Views: 756

Answers (1)

Clemsang
Clemsang

Reputation: 5481

Here is one way :

DF <- data.frame("Name" = c("A","B"), "SN" = 1:2, "Age" = c("21,34,456,567,23,123,34", "15,345,567,3,23,45,67,76,34,34,55,67,78,3"))

apply(DF, 1, function(row){
  aa <- as.numeric(strsplit(row["Age"], ",")[[1]])
  row["mean.aa"] <- mean(aa)
  as.list(row)
})

Upvotes: 1

Related Questions