rownames_to_column在rowwise()正确后不起作用
我有这个 df:
df <- structure(list(a = 1:5, b = 6:10, c = 11:15, d = c("a", "b",
"c", "d", "e"), e = 1:5), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
a b c d e
<int> <int> <int> <chr> <int>
1 1 6 11 a 1
2 2 7 12 b 2
3 3 8 13 c 3
4 4 9 14 d 4
5 5 10 15 e 5
rownames_to_column 作品:
df %>%
column_to_rownames(var="d") %>%
rownames_to_column(var= "d")
# Output
d a b c e
1 a 1 6 11 1
2 b 2 7 12 2
3 c 3 8 13 3
4 d 4 9 14 4
5 e 5 10 15 5
rownames_to_column 工作不正常(返回索引?)
df %>%
column_to_rownames(var="d") %>%
rowwise() %>%
rownames_to_column(var= "d")
# Output:
d a b c e
<chr> <int> <int> <int> <int>
1 1 1 6 11 1
2 2 2 7 12 2
3 3 3 8 13 3
4 4 4 9 14 4
5 5 5 10 15 5
为什么会出现这种行为?
回答
df 本来是小题大做。
class(df)
[1] "tbl_df" "tbl" "data.frame"
当您使用column_to_rownames它时,它会变成一个数据框,因为 tibbles 不能有行名。
df1 <- df %>% column_to_rownames(var="d")
class(df1)
#[1] "data.frame"
接下来,当您使用时rowwise,数据再次转换为 tibble,并且行名现在丢失了。
df2 <- df1 %>% rowwise()
class(df2)
#[1] "rowwise_df" "tbl_df" "tbl" "data.frame"
因此,当您这样做时df2 %>% rownames_to_column(var = 'd'),没有d行名,因此您会得到一个带有行号的列。
rownames(df2)
#[1] "1" "2" "3" "4" "5"