R - function which has a data frame parameter does

2019-09-03 06:10发布

问题:

I make a simple code which can change the index number to name

change_name = function(x) {
  valid_user[match(x, valid_user$id),'name']
}

and apply this function to data.frame.

Data.frame name is 'ga.screen', and the column name is 'dimension1'.

ga.screen[, 'dimension1'] =sapply(ga.screen[, 'dimension1'], change_name)

It works well.

And next I want to make this code function which is be able to apply various case.

readable_user_id = function(data, col) {
  data[, col] = sapply(data[, col], change_name)
}
readable_user_id(ga.screen, 'dimension1')

This is totally same code but the latter one doesn't work!

Why this happens? Is this a sapply problem which doesn't work in function? or Is this data.frame problem which can't be passed as parameter?

回答1:

Your function should return the modified data, try

readable_user_id = function(data, col) {
   data[, col] = sapply(data[, col], change_name)
   data
}