简体   繁体   English

将data.frame中的所有列乘以第一列

[英]multiply all the columns in a data.frame by the first

I need to multiply each column in a data.frame by the values in first column (classfactor). 我需要将data.frame的每一列乘以第一列(classfactor)中的值。

This is my data.frame 这是我的data.frame

sample classfactor 01.BA.V 01.BA.VG 01.BO.VG 01.PR.O 01.TO.VG 02.BA.O 02.BA.V
AB 0.730 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0 0.00000000
AC 0.730 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0 0.00000000
AB 0.002 0.000000000 0.000000000 0.000749929 0.000000000 0.000000000 0 0.00000000
CC 0.730 0.081599145 0.093453018 0.031247022 0.015987076 0.036212483 0 0.02537884
BB 0.730 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0 0.00000000
AA 0.730 0.001533075 0.000108666 0.000000000 0.000364526 0.000241417 0 0.00006340

It has 146 rows and 155 columns. 它有146行和155列。

I can't figure out how to do. 我无法弄清楚该怎么做。 Any suggestions? 有什么建议么?

If I'm not mistaken, you can do 如果我没弄错的话,你可以做到

df[-(1:2)] <- df[["classfactor"]] * df[-(1:2)]

where df is your data frame and the first column is sample ( classfactor is actually the second column). 其中df是您的数据框,第一列是sampleclassfactor实际上是第二列)。

Well, you could start with a loop. 好吧,你可以从一个循环开始。

for(i in 2:length(names(data.frame))) {
    data.frame[,i] <- data.frame[, 1] * data.frame[, i]
}

On a dataset as small as yours, this should be reasonably quick. 在与您一样小的数据集上,这应该相当快。

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

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