R中ddplyr的意外结果

时间:2015-04-05 04:22:27

标签: r plyr

刚开始使用ddplyr {plyr},我遇到了以下问题:

我创建了一个简单的数据框:

require(plyr)
df <- data.frame(day=c('monday', 'tuesday'), week=c(47,48))

现在我跑这个:

ddply(df, .(day), transform,
  b = ifelse(week==47, week, day)
)

我明白了:

      day week  b
1  monday   47 47
2 tuesday   48  2

而我正试图解决这个问题:

      day week        b
1  monday   47       47
2 tuesday   48  tuesday

我认为问题的一部分是我在一列中混合了数字和字符串变量。知道我怎么能得到我想要的结果吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我很惊讶你没有通过设置stringsAsFactors=FALSE来获得预期的结果......这就是我得到的结果:

require(plyr)

df1 <- data.frame(day=c('monday', 'tuesday'), week=c(47,48), stringsAsFactors = TRUE)
df2 <- data.frame(day=c('monday', 'tuesday'), week=c(47,48), stringsAsFactors = FALSE)


ddply(df1, .(day), transform,
  b = ifelse(week==47, week, day)
)

#       day week  b
# 1  monday   47 47
# 2 tuesday   48  2


ddply(df2, .(day), transform,
  b = ifelse(week==47, week, day)
)

#       day week       b
# 1  monday   47      47
# 2 tuesday   48 tuesday

如果你用这种方式转换df1中的因子,你就会得到相同的结果:

df1$day <- as.character(df1$day)
ddply(df1, .(day), transform,
  b = ifelse(week==47, week, day)
)
#       day week       b
# 1  monday   47      47
# 2 tuesday   48 tuesday