更改data.frame格式以标记所有列

时间:2013-11-07 23:37:40

标签: r dataframe

我之前遇到过这个问题并且需要花费很长的时间,现在我想在这里发帖。提前谢谢!

我正在尝试merge()以下带有更大data.frame(未包含)的小型data.frame(名为HelpData)。下面的代码在HelpData中读取,并查看head()str()

HelpData <- structure(list(`(Intercept)` = c(-0.416714383410771, -0.484420889203111, 
0.8852233181836, -0.00573901277840992, 0.819352447999715, -0.0219740206432874, 
-0.725659038472068, 0.842129479134587, 0.231330671497113, 1.67161285063258, 
0.562139877718068, -0.56702368527195, -1.09763116254353, -0.32410756195596, 
0.166964590752782, -0.812461815971089, -0.609301958979508, 0.368263149194526, 
0.964304770606394, -0.887610418600415, -0.555998527038864, -0.0940912475713328, 
0.706094048452952, -0.500888453405431)), .Names = "(Intercept)", row.names = c("CAL_F01", 
"CAL_F17", "CAL_F19", "CAL_F23", "CAL_F43", "CAL_M33", "CAL_M36", 
"COL_P01", "COL_P03", "COL_P05", "COL_P06", "COL_P07", "COL_P08", 
"COL_P09", "COL_P10", "COL_P12", "COL_P13", "PAT_F02", "PAT_F03", 
"PAT_F04", "PAT_F05", "PAT_M02", "PAT_M03", "PAT_M04"), class = "data.frame")

head(HelpData)
str(HelpData)

如HelpData的str()所示,该对象是一个包含24个obs的数据框。 1个变量。 “拦截”列是唯一被识别的列。但是我希望merge()基于未标记的AnimalID字段。下面的代码导致错误

代码:

 colnames(HelpData)<- c("CougarID", "RandInt")

错误:

 “'names' attribute [2] must be the same length as the vector [1]”  This the first coumne is not regonized and thus cannot be named.

更改数据格式的最佳方法是什么,因此我可以拥有相同的两列,但能够为第一列命名?

干杯。

1 个答案:

答案 0 :(得分:1)

您的美洲狮ID存储在行名称中而不是实际上存储在一列数据中。要改变这一点,

HelpData$CougarID = rownames(HelpData)

应该做的伎俩。

然后你也可以推荐:

names(HelpData)[1] = "RandInt"