我敢肯定这已经被问过了,但是我很难找到它。我需要将数据帧子集化为一行,并从相应的列中减去这些值。
实际上,我确实从数据框中的所有相关列中找到了单行的Subtract值,这提供了解决方案(请参阅下文),但是必须有一种更简单的方法,对吗?一个tidyverse
解决方案将是最大的赞赏。
这是一个示例数据帧:
df <- as_tibble(matrix(1:9, 3, 3))
## A tibble: 3 x 3
# V1 V2 V3
# <int> <int> <int>
#1 1 4 7
#2 2 5 8
#3 3 6 9
减去大小相等的数据帧是没有问题的。
df - df
# V1 V2 V3
#1 0 0 0
#2 0 0 0
#3 0 0 0
但是,当我将子集划分df
为一行并尝试相减时,它无法减去不均匀的数据帧。我子集df
为
df[1, ]
## A tibble: 1 x 3
# V1 V2 V3
# <int> <int> <int>
#1 1 4 7
我想要的解决方案将从第一列的每个值中减去1,从第二列的每个值中减去4,从第三列的每个值中减去7,这样得出的结果是:
## A tibble: 3 x 3
# V1 V2 V3
# <int> <int> <int>
#1 0 0 0
#2 1 1 1
#3 2 2 2
尝试此操作将导致错误:
df - df[1, ]
#Error in Ops.data.frame(df, df[1, ]) :
# ‘-’ only defined for equally-sized data frames
在上面的链接中,我找到了此解决方案,该解决方案有效:
as_tibble(Map(`-`, df, df[1, ]))
## A tibble: 3 x 3
# V1 V2 V3
# <int> <int> <int>
#1 0 0 0
#2 1 1 1
#3 2 2 2
但是,这种解决方案似乎真的很复杂,并且不容易集成到一系列管道中。
有人有什么想法吗?
我们可以复制col
数据集索引的行基。这使两个数据集具有相同的长度/维度
df - unlist(df[1,])[col(df)]
# V1 V2 V3
#1 0 0 0
#2 1 1 1
#3 2 2 2
如果我们需要tidyverse选项,map2
可以使用
library(purrr)
library(dplyr)
map2_df(df, df[1, ], `-`)
# A tibble: 3 x 3
# V1 V2 V3
# <int> <int> <int>
#1 0 0 0
#2 1 1 1
#3 2 2 2
或另一个选择是 uncount
df - uncount(df[1, ], nrow(df))
或使用管道
df %>%
slice(1) %>%
uncount(nrow(df)) %>%
{df - .}
# V1 V2 V3
#1 0 0 0
#2 1 1 1
#3 2 2 2
或搭配 mutate_all
df %>%
mutate_all(list(~ . - first(.)))
# A tibble: 3 x 3
# V1 V2 V3
# <int> <int> <int>
#1 0 0 0
#2 1 1 1
#3 2 2 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句