簡體   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