基于R中其他行的计算添加新行

pwuypxnk  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(90)

假设我有一个简单的dataframe,如下所示:

ID     number
A1       5
A2       10
B1       7
C4       3
D8       2

我必须对dataframe进行一些维护,方法是根据另一行的精确值或multiple的计算来添加新行。例如,如果我需要创建以下行:

ID=B2, number= B1's number
ID=C7, number= C4's number
ID=A3, number= (A1's number+A2's number)/2
ID=C9, number= A2's number

将这些行添加到dataframe将产生以下结果:

ID     number
A1       5
A2       10
B1       7
C4       3
D8       2
B2       7
C7       3
A3      7.5
C9      10

我如何创建这些新行,从 Dataframe 中计算值并在ID列中添加新的ID s?最好是可伸缩的,这样我就可以根据我的公式生成尽可能多的新行,并且最好使用dplyrtidyverse

jchrr9hc

jchrr9hc1#

创建一个新的 Dataframe ,然后将其堆叠在原始 Dataframe 下。如果要手工编码(因为似乎没有可编程模式),我喜欢tribble()函数用于按行创建表:

library(tibble)
# ID=B2, number= B1's number
# ID=C7, number= C4's number
# ID=A3, number= (A1's number+A2's number)/2
# ID=C9, number= A2's number
rbind(df, 
  tribble(
    ~ID, ~number,
    "B2", df[df$ID == "B1", "number"],
    "C7", df[df$ID == "C4", "number"],
    "A3", (df[df$ID == "A1", "number"] + df[df$ID == "A2", "number"]) / 2,
    "C9", df[df$ID == "A2", "number"],
  )
)
#   ID number
# 1 A1    5.0
# 2 A2   10.0
# 3 B1    7.0
# 4 C4    3.0
# 5 D8    2.0
# 6 B2    7.0
# 7 C7    3.0
# 8 A3    7.5
# 9 C9   10.0

您可以使用with()和上面的方法来保存大量的输入:

with(df, rbind(df, 
  tribble(
    ~ID, ~number,
    "B2", number[ID == "B1"],
    "C7", number[ID == "C4"],
    "A3", (number[ID == "A1"] + number[ID == "A2"]) / 2,
    "C9", number[ID == "A2"],
  )
))
nfeuvbwi

nfeuvbwi2#

我们可以使用bind_rows并在创建这些行的 Dataframe 后绑定df和所需的行:

library(dplyr)

bind_rows(df, data.frame(
  ID = c("B2", "C7", "A3", "C9"),
  number = c(df$number[3], df$number[4], (df$number[1] + df$number[2])/2, df$number[2])
))
ID number
1 A1    5.0
2 A2   10.0
3 B1    7.0
4 C4    3.0
5 D8    2.0
6 B2    7.0
7 C7    3.0
8 A3    7.5
9 C9   10.0

另一种选择是使用add_row()

df %>%
  add_row(ID = "B2", number = df$number[3]) %>%
  add_row(ID = "C7", number = df$number[4]) %>%
  add_row(ID = "A3", number = (df$number[1] + df$number[2])/2) %>%
  add_row(ID = "C9", number = df$number[2])

 ID number
1 A1    5.0
2 A2   10.0
3 B1    7.0
4 C4    3.0
5 D8    2.0
6 B2    7.0
7 C7    3.0
8 A3    7.5
9 C9   10.0

相关问题