将较短的列添加到R中的数据帧
我有两个数据帧: a b 我想将列n从数据帧a)传输到数据帧b),这样我就可以得到:将较短的列添加到R中的数据帧,r,dataframe,R,Dataframe,我有两个数据帧: a b 我想将列n从数据帧a)传输到数据帧b),这样我就可以得到: Group n 1 3 1 3 1 3 2 3 2 3 2 3 3 4 3 4 3 4 3 4 如何使用R实现这一点 谢谢 像这样 library(tidyverse) df1 <- tribble(~"Group", ~"n", 1, 3,
Group n
1 3
1 3
1 3
2 3
2 3
2 3
3 4
3 4
3 4
3 4
如何使用R实现这一点
谢谢 像这样
library(tidyverse)
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
df3 <- dplyr::left_join(df1, df2, by = "Group")
df3
## A tibble: 9 x 2
# Group n
# <dbl> <dbl>
#1 1 3
#2 1 3
#3 1 3
#4 2 3
#5 2 3
#6 2 3
#7 3 4
#8 3 4
#9 3 4
库(tidyverse)
谢谢,这正是我想要的!有没有一种方法可以在不复制数据帧的情况下执行此操作?这已经非常有用了。你说的“不复制数据帧”是什么意思?数据帧大吗?(即数百万行)你是说我是如何创建df1/df2的?如果您已经有数据,则不需要创建数据-这只是为了展示一个您可以实施的策略示例-如果您已经有两个数据帧,并且它们都包含一个名为“Group”的列,则您可以使用new_dataframe太好了,谢谢!这正是我试图连贯地表达的问题。这真的很有帮助!不客气。
Group n
1 3
1 3
1 3
2 3
2 3
2 3
3 4
3 4
3 4
3 4
library(tidyverse)
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
df3 <- dplyr::left_join(df1, df2, by = "Group")
df3
## A tibble: 9 x 2
# Group n
# <dbl> <dbl>
#1 1 3
#2 1 3
#3 1 3
#4 2 3
#5 2 3
#6 2 3
#7 3 4
#8 3 4
#9 3 4
#install.packages("microbenchmark")
library(microbenchmark)
#install.packages("data.table")
library(data.table)
dplyr_func <- function(){
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
left_join(df1, df2, by = "Group")
}
dt_func <- function(){
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
df1 <- setDT(df1)
df2 <- setDT(df2)
df3 <- df1[df2, on='Group']
}
microbenchmark(dplyr_func(), dt_func())
#Unit: milliseconds
# expr min lq mean median uq max neval
# dplyr_func() 2.860449 3.005662 3.550877 3.183445 3.444416 16.001694 100
# dt_func() 1.479301 1.570013 1.808001 1.698145 1.807476 6.958431 100