我正在寻找一种更好,更有效的解决方案,以从数据帧(df1)的每一行中减去一个向量。我当前的解决方案是重复向量(Vec)以创建一个长度与df1相似的数据帧(Vec_df1),然后将两个数据帧相减。现在,我想知道是否有一种更“直接”的方法无需创建新的Vec_df1数据帧(最好在tidyverse中)即可。请参阅下面的示例数据。
#Example data
V1 <- c(1, 2, 3)
V2 <- c(4, 5, 6)
V3 <- c(7, 8, 9)
df1 <- tibble(V1, V2, V3)
Vec <- c(1, 1, 2)
# Current solution, creates a dataframe with the same nrows by repeating the vector.
Vec_df1 <- tibble::as_tibble(t(Vec)) %>%
dplyr::slice(rep(dplyr::row_number(), nrow(df1)))
# Subtraction.
df2 <- df1-Vec_df1
df2
预先感谢
答案 0 :(得分:3)
我们可以使用sweep
:
sweep(df1, 2, Vec, `-`)
# `-` is default FUN in sweep so you can also use
#sweep(df1, 2, Vec)
# V1 V2 V3
#1 0 3 5
#2 1 4 6
#3 2 5 7
或与您类似的尝试
df1 - rep(Vec, each = nrow(df1))
答案 1 :(得分:3)
使用map2_df()
的类似方法:
library(purrr)
map2_df(df1, Vec, `-`)
# A tibble: 3 x 3
V1 V2 V3
<dbl> <dbl> <dbl>
1 0 3 5
2 1 4 6
3 2 5 7
答案 2 :(得分:0)
我们也可以
df1 - Vec[col(df1)]