Why does transform fail silently?

巧了我就是萌 提交于 2019-12-13 19:31:53

问题


Say I have a frame with a column of dates:

test.frame$alt_dates <- c('2001-01-04', '2001-05-11', '2001-05-14', '2001-07-24', '2003-12-24', '2004-07-21', '2004-10-15', '2004-12-15', '2005-03-17', '2005-07-18')

They start out as characters. Okay:

class(test.frame$alt_dates)
[1] "character"

If I try to use transform to make those dates into dates:

transform(test.frame, alt_dates <- as.Date(alt_dates)

R just prints my frame to the console. If I transform the column directly it works fine:

test.frame$alt_dates <- as.Date(test.frame$alt_dates)
class(test.frame$alt_dates)
[1] "Date"

What am I doing wrong with Transform?

UPDATE: As a few folks noticed, I wasn't assigning the results to anything. So that explains the printing to the screen and the not storing any changes. But it doesn't work even if I do capture the results:

test.frame <- transform(test.frame, more_dates <- as.Date(more_dates))
class(test.frame$more_dates)
[1] "character"

回答1:


As @Andrie and @StephanKolassa say, you need to assign the result. However, you are making another mistake in your use of transform which happens to work in this context but will bite you in almost any other case. <- and = are not interchangeable in this context. You should use = with transform (in this case I think it works because the test data frame only has a single column!)

test.frame <- data.frame(alt_dates=c('2001-01-04', '2001-05-11', '2001-05-14', 
  '2001-07-24', '2003-12-24', '2004-07-21', '2004-10-15', '2004-12-15', 
  '2005-03-17', '2005-07-18'))
test.frame <- transform(test.frame,alt_dates=as.Date(alt_dates))



回答2:


transform() does not fail. R uses call by value, i.e., arguments to functions are transferred by value only - the original object test.frame$alt.dates is not transferred. Arguments to functions can therefore not be changed by the function. The alternative, call by reference, would allow a function to modify its parameters in the outer scope. In other programming languages such as C, call by reference is done by passing "pointers" to memory addresses. Not in R.

Simply assign the result of transform() to the original object.



来源:https://stackoverflow.com/questions/13634437/why-does-transform-fail-silently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!