2016-09-25 62 views
1

我有一个数字和字符列的数据框,我想绝对字符向量,以便它不返回列名称和因子级别,当我选择数据后。在R中创建数据框之后如何隔离字符向量?

我的问题是,我创建了包含数值,布尔值和字符值的矢量的数据帧,因此我无法在此阶段使用绝缘功能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 <- 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 
+0

重要的是,那个名字是一个因素? 因为比stringAsFactor = FALSE和data.frame,而不是as.data.frame它应该工作 –

+0

@Benjamin,不,因为'df $ name [1]'仍然返回列的名称和级别信息 – Florent

+0

对不起,我把stringAsFactor选项搞乱data.frame。现在工作! – Florent

回答

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) 

和随后而不是as.data.frame使用data.frame与参数stringAsFactor=FALSE

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

创建data.frame DF以及与stringAsFactor=False产量则下列:

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 
相关问题