【问题标题】:Extracting factor labels from table result for use as data frame column从表结果中提取因子标签以用作数据框列
【发布时间】:2013-01-21 15:00:00
【问题描述】:

我正在使用原始行输入格式 UID=character, Win/Lose=Boolean 进行点击流日志文件摘要。我要创建的输出摘要是表单行 UID、sumWin、sumLose。我已经使用表格来获得我想要的部分内容,但是我无法找出正确的语法来从表格结果中提取因子标签以用于摘要 df。下面的示例构建了一个小测试用例并显示了我卡住的地方:我无法从表格结果中获取因子标签。 (当然,您认为有更好的方法来处理整个事情 - 这显然也非常有用!)

我在这里的编辑器中仍然无法格式化 - 显然这是我接下来需要问的问题......!

foo <- data.frame(Uid=character(4), Win=logical(4), stringsAsFactors=FALSE)  
  foo$Uid <- c("UidA", "UidB", "UidA", "UidC")  
  foo$Win <- c(FALSE, TRUE, TRUE, FALSE)  
  #display foo  
  foo  
   Uid   Win  
1 UidA FALSE  
2 UidB  TRUE  
3 UidA  TRUE  
4 UidC FALSE  

  # my desired summary df is, for each UID: NWin (foo$Win=TRUE), NRunUp (foo$Win=FALSE)   
  # here I initialise a holder for it  
  fooNUniques <- length(unique(foo$Uid))  
  fooSummary <- data.frame(Uids=character(fooNUniques),NWins=numeric(fooNUniques),NRunUps=numeric(fooNUniques))   
  fooSummary

  Uids NWins NRunUps

1          0       0  
2          0       0  
3          0       0  
  #I can reference in to the result of applying table to get part of what I want  
  #First I get the table, this gets me a table by win/lose value  
  fooTable <- table(foo$Uid, foo$Win)  
  fooTable  

         FALSE TRUE  
  UidA     1    1  
  UidB     0    1  
  UidC     1    0  

  # I can get at the actual results via unname which gives me a matrix  
  fooTableAsMat <- unname(fooTable)  
  fooTableAsMat  
     [,1] [,2]  
[1,]    1    1  
[2,]    0    1  
[3,]    1    0  

  #but the UID vec is hidden in the table structure *somewhere* and   
  # I can't work out how to reference it out  

  #coercing the result to a dataFrame doesn't work

  as.data.frame(fooTable)  
    Var1  Var2 Freq  
  1 UidA FALSE    1  
  2 UidB FALSE    0  
  3 UidC FALSE    1  
  4 UidA  TRUE    1  
  5 UidB  TRUE    1  
  6 UidC  TRUE    0  

  #I have also tried 'aggregate' but have not made friends with it

【问题讨论】:

  • 你不能只用reshape2::dcast as.data.frame(fooTable) 来获取宽格式吗?或者这不是你想要的?
  • 也许这确实可以满足我的要求。什么是宽幅面?我在 R 帮助中找不到它。
  • 在 reshape 文档下间接找到了宽格式。但我似乎没有 reshape2 因为我在帮助中找不到它(也许我需要安装一个库?)。 as.data.frame 似乎实际上撤消了分析,所以我不确定它作为中间步骤是否有效,除非 dcast 以某种方式修改其操作?
  • fooTable的行名可以通过rownames(fooTable)访问。
  • 谢谢斯文!所以现在我有一个快速补丁。而且,从 Arun 那里学到了一些新东西,这意味着我将来不必修补它。 (更少的转换 = 更少的错误空间和更多的空间来处理其他事情。)

标签: r dataframe syntax r-factor


【解决方案1】:

这有帮助吗?

使用plyr

> ddply(foo, .(Uid), summarise, NWin = sum(Win), NRunUp = sum(!Win))
#    Uid NWin NRunUp
# 1 UidA    1      1
# 2 UidB    1      0
# 3 UidC    0      1

【讨论】:

  • 是的!我的 q 的潜台词是,最好不要再用头撞墙,而是学习 plyr(或 data.table)...;-) 看起来这个问题的答案是“是”!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-11
相关资源
最近更新 更多