【问题标题】:R - Exctracting a vector of doubles from data.frameR - 从 data.frame 中提取双精度向量
【发布时间】:2014-10-04 16:53:07
【问题描述】:

我使用read.table()header=T 得到了这个问题,试图从data.frameas.double(as.character()) 中提取双精度向量(参见?factor)。

但这只是如何我意识到我不理解 R 的逻辑。所以你不会看到例如read.table 在下面的代码中,只有必要的部分。你能告诉我以下选项有什么区别吗?

  1. header=T 等效:

    (a <- data.frame(array(c(0.5,0.5,0.5,0.5), c(1,4))))
    as.character(a)
    # [1] "0.5" "0.5" "0.5" "0.5"
    
  2. 没有header=T 等效:

    b <- data.frame(array(c("a",0.5,"b",0.5,"c",0.5,"d",0.5), c(2,4)))
    (a <- b[2,])
    as.character(a)
    # [1] "1" "1" "1" "1"
    
    (a <- data.frame(a, row.names=NULL)) # now there's not even a visual difference
    as.character(a)
    # [1] "1" "1" "1" "1"
    

【问题讨论】:

  • 您正在与factors 打交道。将stringsAsFactors = FALSE 添加到您的data.frame 步骤中并进行比较。
  • 使用read.table 和变体时的stringsAsFactors 转换是常见的混淆来源。与往常一样,在您的数据上使用str 以准确了解您正在处理的内容可能非常有价值。一旦您了解了stringsAsFactors 参数,它就会成为一个非常有用的工具。如果您选择options(stringsAsFactors = FALSE),也可以全局设置选项。
  • 哇,谢谢。我会阅读因素。

标签: r class dataframe double character


【解决方案1】:

问题在于data.frame 的默认设置,其中一个选项stringsAsFactors 设置为TRUE。这是您的方案中的一个问题,因为当您使用 header = FALSE 时,该行中存在的字符值会将整个列强制转换为字符,然后将其转换为因子(除非您设置 stringsAsFactors = FALSE)。

这里有一些可以玩的例子:

## Two similar `data.frame`s -- just one argument different

b <- data.frame(array(c("a",0.5,"b",0.5,"c",0.5,"d",0.5), c(2,4)))
b2 <- data.frame(array(c("a",0.5,"b",0.5,"c",0.5,"d",0.5), c(2,4)),
                stringsAsFactors = FALSE)

## First with "b"

as.character(b[2, ])
# [1] "1" "1" "1" "1"

sapply(b[2, ], as.character)
#    X1    X2    X3    X4 
# "0.5" "0.5" "0.5" "0.5"
as.matrix(b)[2, ]
#    X1    X2    X3    X4 
# "0.5" "0.5" "0.5" "0.5"
as.double(as.matrix(b)[2, ])
# [1] 0.5 0.5 0.5 0.5

## Now with "b2"

as.character(b2[2, ])
# [1] "0.5" "0.5" "0.5" "0.5"
as.double(as.character(b2[2, ]))
# [1] 0.5 0.5 0.5 0.5

【讨论】:

  • 感谢您的回答。我现在在?read.table / colClasses 中看到这个假设(顺便提到)它是应该属于同一类的数据的。有没有办法将其更改为行?你知道我对此表示怀疑,但它可能很有趣。 (对于类似的假设是否有很好的帮助?)
  • @9877126,我不知道。 lists 让您存储不同类型的信息。 (其实data.framelist的一种特殊类型。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多