将数据框行转换为字符向量时出错 [英] Error when converting dataframe row to character vector
问题描述
所以我有以下数据框datafr。
So I've got the following dataframe, datafr.
X1 X2 X1.1 X2.1
Composite Element Composite Element
14-3-3_epsilon-M-C -0.8660101895 14-3-3_epsilon-M-C -0.6814387425
4E-BP1_pS65-R-V 0.1056560215 4E-BP1_pS65-R-V 0.1787506005
4E-BP1_pT37T46-R-V 0.6408257495 4E-BP1_pT37T46-R-V -0.7485933875
4E-BP1_pT70-R-C 0.6413568085 4E-BP1_pT70-R-C 0.9554481415
我想将第二行作为列名,所以我看一下行
I want to make the second row the column names, so I look at the row
datafr[1,]
一切都是应有的
X1 X2 X1.1 X2.1
Composite Element Composite Element
但是,当我将其转换为字符向量时,我得到的单词变成了数字...
However, when I convert this to a character vector I get the words changing to numbers...
as.character(c(datafr[1,]))
[1] "49" "161" "49" "161"
这是怎么回事?
推荐答案
问题是您的data.frame列不是字符而是因素(请阅读R简介的区别。)
The problem is that your data.frame columns are not characters but factors (read about the difference in the R introduction.)
您必须这样做:
as.character(unlist(datafr[1, ]))
获取当前数据的字符向量。但是,您可能想在代码上游解决问题:
to get a character vector out ot your current data. However, you might want to fix your problem upstream within your code:
您可以尝试确保data.frame首先不包含因子。通常,这是通过在 data.frame
,之类的函数中添加
, stringsAsFactors = FALSE
来完成的。 as.data.frame read.table
, read.csv
用过它们。如果您在某处使用 read.table
,我强烈建议您也考虑使用 header = TRUE
来获取名称。首先在您想要的位置。
You could try to make sure that your data.frame does not contain factors in the first place. Most often, this is done by adding stringsAsFactors = FALSE
to functions like data.frame
, as.data.frame
, read.table
, read.csv
where you might have used them. If you used read.table
somewhere, I would highly suggest you also look at using header = TRUE
to get the colnames where you wanted in the first place.
这篇关于将数据框行转换为字符向量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!