[英]In R, adding a new row to dataframe, to each id
我有以下數據框:
df = data.frame(id = rep(101:110, each = 2),
variable = rep(c('a','b'), times = 2),
score = rnorm(1))
對於每個id,我想在“變量”中添加值“ c”,並在“得分”中添加100。 我發現的唯一方法是使用rbind。
df_helper = data.frame(id = unique(df$id),
variable = 'c',
score = 100)
rbind(df, df_helper)
這不是很優雅,因為我需要定義另一個數據框。 有更好的主意嗎?
tidyverse
方法將是:
library(tidyverse)
df %>%
spread(variable,score) %>%
mutate(c = 100) %>%
gather(variable,score, - id)
# id variable score
# 1 101 a -0.1831428
# 2 102 a -0.1831428
# 3 103 a -0.1831428
# 4 104 a -0.1831428
# 5 105 a -0.1831428
# 6 106 a -0.1831428
# 7 107 a -0.1831428
# 8 108 a -0.1831428
# 9 109 a -0.1831428
# 10 110 a -0.1831428
# 11 101 b -0.1831428
# 12 102 b -0.1831428
# 13 103 b -0.1831428
# 14 104 b -0.1831428
# 15 105 b -0.1831428
# 16 106 b -0.1831428
# 17 107 b -0.1831428
# 18 108 b -0.1831428
# 19 109 b -0.1831428
# 20 110 b -0.1831428
# 21 101 c 100.0000000
# 22 102 c 100.0000000
# 23 103 c 100.0000000
# 24 104 c 100.0000000
# 25 105 c 100.0000000
# 26 106 c 100.0000000
# 27 107 c 100.0000000
# 28 108 c 100.0000000
# 29 109 c 100.0000000
# 30 110 c 100.0000000
我們可以使用bind_rows
library(tidyverse)
bind_rows(df, df_helper)
如果沒有“ df_helper”數據集,一種方法是
df %>%
group_by(id) %>%
nest %>%
mutate(data = map(data, ~
.x %>%
bind_rows(tibble(variable = "c", score = 100)))) %>%
unnest
# A tibble: 30 x 3
# id variable score
# <int> <chr> <dbl>
# 1 101 a -0.778
# 2 101 b -0.778
# 3 101 c 100
# 4 102 a -0.778
# 5 102 b -0.778
# 6 102 c 100
# 7 103 a -0.778
# 8 103 b -0.778
# 9 103 c 100
#10 104 a -0.778
# ... with 20 more rows
或帶有data.table的另一個選項。 按“ id”分組,將“ c”和100分別連接到末尾的每一列
library(data.table)
setDT(df)[, .(variable = c(variable, 'c'), score = c(score, 100)), by = id]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.