首页 > 解决方案 > 算术数据框和向量

问题描述

如果我有一个数据框,比如 iris,并且我想减去一个具有相同列名的向量,我该怎么做?

df <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
    1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
    0.2, 0.2, 0.4)), row.names = c(NA, 6L), class = "data.frame")

vec <- tibble(Sepal.Length = 1, Sepal.Width = 2, Petal.Length = 3, Petal.Width = 4)

我想做这样的事情df - vec

标签: rdataframe

解决方案


或者:

map_dfc(seq_along(colnames(df)), ~df[[.x]] - vec[[.x]])

推荐阅读