dplyr :: mutate更改行号,如何保留它们?

时间:2018-04-06 18:54:18

标签: r dplyr row-number mutate

我在tibble上使用lme4 :: lmList来获取我数据中为每个主题(id)拟合的线性拟合线的系数。我真正想要的是一个很好的长链管道,因为我不想保留任何这个输出,只是用于斜率/截距图。但是,我遇到了一个问题。 lmList正在创建一个数据框,其中行号是原始主题ID号。我希望保留这些信息,但是一旦我在输出上使用mutate,行号就会从1开始变为顺序。我尝试先使用rowid_to_column来解救它们,但这只是给了我一列来自1的连续数字。我可以做什么,除了掏出管道并将它们放入带有底座R的柱子中?独一无二(a_df $ id)真的是最好的解决方案吗?我在这里环顾四周,但没有看到像这样的问题。

library(tibble)
library(dplyr)
library(Matrix)
library(lme4)
a_df <- tibble(id = c(rep(4, 3), rep(11, 3), rep(12, 3), rep(42, 3)),
          age = c(rep(seq(1, 3), 4)),
          hair = 1 + (age*2) + rnorm(12) + as.vector(sapply(rnorm(4), function(x) rep(x, 3))))

# as.data.frame to get around stupid RStudio diagnostics bug
int_slope <- coef(lmList(hair ~ age | id, as.data.frame(a_df))) %>%
  setNames(., c("Intercept", "Slope"))
# Notice how the row numbers are the original subject ids?
print(int_slope)

    Intercept    Slope
4   2.9723596 1.387635
11  0.2824736 2.443538
12 -1.8912636 2.494236
42  0.8648395 1.680082

int_slope2 <- int_slope %>% mutate(ybar = Intercept + (mean(a_df$age) * Slope))
# Look!  Mutate has changed them to be the numbers 1 to 4
print(int_slope2)

   Intercept    Slope     ybar
1  2.9723596 1.387635 5.747630
2  0.2824736 2.443538 5.169550
3 -1.8912636 2.494236 3.097207
4  0.8648395 1.680082 4.225004

# Try to rescue them with rowid_to_column
int_slope3 <- int_slope %>% rowid_to_column(var = "id")
# Nope, 1 to 4 again
print(int_slope3)

  id  Intercept    Slope
1  1  2.9723596 1.387635
2  2  0.2824736 2.443538
3  3 -1.8912636 2.494236
4  4  0.8648395 1.680082

谢谢,

SJ

3 个答案:

答案 0 :(得分:2)

dplyr/tidyverse宇宙doesn't "believe in" row names。任何对观察很重要的数据都应包含在一列中。 tibble包中包含将行名称移动到列中的功能。尝试

int_slope %>% rownames_to_column()

在任何变异之前。

答案 1 :(得分:0)

没有什么比寻求帮助让你看到答案了。那些不是行号,它们是数字行名。他们当然是!不连续的行号没有意义。 rownames_to_column是我的答案。

答案 2 :(得分:-1)

为什么你不在int_slope上创建另一个'ybar'列?

int_slope$ybar<- Intercept + mean(a_df$age) * Slope