繁体   English   中英

使用R中的行组为简单方程式的结果添加新行

[英]Add new row for the result of a simple equation using row groups in R

我在完成这个简单的任务时遇到了麻烦。

在以下data.frame ,如何为每列添加包含Sepal.Length*0.75 + Sepal.Width*0.25结果的额外行? 谢谢

as.data.frame(t(iris[1:5,1:4]))
               1   2   3   4   5
Sepal.Length 5.1 4.9 4.7 4.6 5.0
Sepal.Width  3.5 3.0 3.2 3.1 3.6
Petal.Length 1.4 1.4 1.3 1.5 1.4
Petal.Width  0.2 0.2 0.2 0.2 0.2

@akrun的答案似乎是最好的答案,但是,如果您只想使用最终数据集,则可以使用行引用-

x <- as.data.frame(t(iris[1:5,1:4]))
x[c('new'),] <- x[c('Sepal.Length'), ]*0.75 + x[c('Sepal.Width'), ]*0.25

我们需要在转置之前创建一列,因为t将转换为matrix并且matrix只能容纳单个class 由于“ iris”的第五列不是“数字”,因此在进行转置时,整个matrix将转换为character 因此,与其在事后进行计算,不如在转置之前进行计算

df1 <- iris[1:5,]
df1$new <- with(df1, Sepal.Length * 0.75 + Sepal.Width *25)
t(df1)

更新资料

基于更新后的结构,我们基于行名对矩阵“ m1”的行进行子集化,并使用原始矩阵进行计算和rbind

m1 <- as.data.frame(t(iris[1:5,1:4]))
m2 <- rbind(m1, new = m1["Sepal.Length",] * 0.75 + m1["Sepal.Width", ] * 0.25)
m2
#              1     2     3     4    5
#Sepal.Length 5.1 4.900 4.700 4.600 5.00
#Sepal.Width  3.5 3.000 3.200 3.100 3.60
#Petal.Length 1.4 1.400 1.300 1.500 1.40
#Petal.Width  0.2 0.200 0.200 0.200 0.20
#new          4.7 4.425 4.325 4.225 4.65

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM