将 row.names 从 num 更改为 chr
Change row.names from num to chr
我在 R 中有一个 data.frame,row.names 是一个字符,我希望它们是数字。我试图找到与 相同的问题,但它不起作用。
这是我的代码:
attr(DF1, "row.names")
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20"
在我执行以上链接后:
DF1$id <- as.integer(row.names(DF1))
DF1[order(DF1$id), ]
我得到相同的结果:
attr(DF1, "row.names")
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20"
我希望结果与数据帧 D2 中的结果相同:
attr(DF2, "row.names")
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
从帮助页面 ?rownames
它说(强调我的)
For a data frame, value for rownames should be a character vector of non-duplicated and non-missing names (this is enforced), and for colnames a character vector of (preferably) unique syntactically-valid names. In both cases, value will be coerced by as.character, and setting colnames will convert the row names to character.
你可以像这样把它们变成一个整数。
df <- data.frame(x = 1:3)
rownames(df) <- as.character(5:7)
attr(df, "row.names")
#> [1] "5" "6" "7"
rownames(df) <- as.integer(rownames(df))
attr(df, "row.names")
#> [1] 5 6 7
请注意 row.names
总是 return 一个字符向量。参见 ?row.names
。
row.names(df)
#> [1] "5" "6" "7"
我在 R 中有一个 data.frame,row.names 是一个字符,我希望它们是数字。我试图找到与
这是我的代码:
attr(DF1, "row.names")
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20"
在我执行以上链接后:
DF1$id <- as.integer(row.names(DF1))
DF1[order(DF1$id), ]
我得到相同的结果:
attr(DF1, "row.names")
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20"
我希望结果与数据帧 D2 中的结果相同:
attr(DF2, "row.names")
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
从帮助页面 ?rownames
它说(强调我的)
For a data frame, value for rownames should be a character vector of non-duplicated and non-missing names (this is enforced), and for colnames a character vector of (preferably) unique syntactically-valid names. In both cases, value will be coerced by as.character, and setting colnames will convert the row names to character.
你可以像这样把它们变成一个整数。
df <- data.frame(x = 1:3)
rownames(df) <- as.character(5:7)
attr(df, "row.names")
#> [1] "5" "6" "7"
rownames(df) <- as.integer(rownames(df))
attr(df, "row.names")
#> [1] 5 6 7
请注意 row.names
总是 return 一个字符向量。参见 ?row.names
。
row.names(df)
#> [1] "5" "6" "7"