为什么transform会默默地失败? [英] Why does transform fail silently?

查看:40
本文介绍了为什么transform会默默地失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有日期列的框架:

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 只是将我的框架打印到控制台.如果我直接转换列它工作正常:

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"

我在使用 Transform 时做错了什么?

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"

推荐答案

正如@Andrie 和@StephanKolassa 所说,您需要分配结果.但是,您在使用 transform 时犯了另一个错误,碰巧在这种情况下可以工作,但几乎在任何其他情况下都会咬你.<-= 在此上下文中不可互换.您应该将 =transform 一起使用(在这种情况下,我认为它有效,因为测试数据框只有一列!)

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))

这篇关于为什么transform会默默地失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆