gpt4 book ai didi

r - 将数据帧的每一列乘以向量的对应值

转载 作者:行者123 更新时间:2023-12-02 03:41:06 26 4
gpt4 key购买 nike

我有以下数据框和向量:

dframe <- as.data.frame(matrix(1:9,3))
vector <- c(2,3,4)

我想将 dframe 的每一列相乘通过vector的对应值。这是不行的:

> vector * dframe
V1 V2 V3
1 2 8 14
2 6 15 24
3 12 24 36

dframe 的每乘以vector对应的值,而不是每个。有没有惯用的解决方案,或者我是否坚持 for循环?

最佳答案

这是使用sweep的另一个选项

sweep(dframe, 2, vector, "*")
# V1 V2 V3
#1 2 12 28
#2 4 15 32
#3 6 18 36
<小时/>

或者使用col

dframe*vector[col(dframe)]

关于r - 将数据帧的每一列乘以向量的对应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43189087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com