【问题标题】:How to insulate a character vector after a dataframe is created in R?在 R 中创建数据帧后如何隔离字符向量?
【发布时间】:2016-09-25 09:40:09
【问题描述】:

我有一个包含数字和字符列的数据框,我想隔离字符向量,以便在我之后选择数据时它不会返回列名和因子级别。

我的问题是我使用包含数字、布尔值和字符值的向量创建数据框,因此在这个阶段我不能使用绝缘函数 I()

conf1 <- c(name = "conf1", num = 1, bool = TRUE)
conf2 <- c(name = "conf2", num = 10, bool = TRUE)
conf3 <- c(name = "conf3", num = 100, bool = FALSE)

conf1 <- as.data.frame(t(conf1))
conf2 <- as.data.frame(t(conf2))
conf3 <- as.data.frame(t(conf3))

df <- cbind(conf1, conf2, conf3)

数据框已创建,现在我希望 df[1,]$name 仅返回 "conf1" 而不是所有级别的列名。

df
   name num  bool
1 conf1   1  TRUE
2 conf2  10  TRUE
3 conf3 100 FALSE

df[1,]$name
 name 
conf1 
Levels: conf1 conf2 conf3

是否有可能在不使用像 name &lt;- I(c("conf1", "conf2", "conf3")) 这样的 100% 字符向量创建数据帧的情况下做到这一点? (即我想根据配置对数据进行分组)

看来我无法将向量直接与数据框隔离:

df$name <- I(df$name)

谢谢

编辑:我可以将数据转换为数字和字符,但这个解决方案不符合我的需要,因为它会重载我的代码(即我从许多行和列中选择值)。

> as.character(df[1,]$name)
[1] "conf1"

> as.numeric(df[1,]$num)
[1] 1

【问题讨论】:

  • 重要的是,名字是一个因素吗?因为与 stringAsFactor=FALSE 和 data.frame 而不是 as.data.frame 相比,它应该可以工作
  • @Benjamin,不,因为df$name[1] 仍然返回列的名称和级别信息
  • 对不起,我弄乱了 data.frame 中的 stringAsFactor 选项。现在可以使用了!

标签: r dataframe


【解决方案1】:

正如我的命令中提到的。如果不需要,该名称是一个因素,以下是可行的:

conf1 <- c(name = "conf1", num = 1, bool = TRUE)
conf2 <- c(name = "conf2", num = 10, bool = TRUE)
conf3 <- c(name = "conf3", num = 100, bool = FALSE)

然后使用带有参数stringAsFactor=FALSEdata.frame 代替as.data.frame

conf1 <- data.frame(t(conf1), stringsAsFactors = FALSE)
conf2 <- data.frame(t(conf2), stringsAsFactors = FALSE)
conf3 <- data.frame(t(conf3), stringsAsFactors = FALSE)

使用stringAsFactor=False 创建data.frame df 会产生以下结果:

df <- data.frame(rbind(conf1,conf2,conf3), stringsAsFactors = FALSE)
 df$name[1]
[1] "conf1"

Df 看起来像这样:

> df
   name num  bool
1 conf1   1  TRUE
2 conf2  10  TRUE
3 conf3 100 FALSE

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2014-05-27
    • 2014-08-05
    • 2022-12-03
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多