R将列乘以第二个数据帧中的值

时间:2014-01-29 10:36:55

标签: r dataframe

我有两个数据帧: DF1

plot   grass moss   rock    other     stuff  
a      4      0     0       text      3
b      2      2     3       text      4
c      10     0     0       text      0
d      3      1     0       text      9

和 DF2

Cover  value
grass   5
moss    2
rock    3

我想将df1中的值乘以df2中的相应值。 该解决方案应适用于大型数据集。

结果 DF3

plot  grass moss    rock    
a     20      0     0      
b     10      4     9      
c     50      0     0       
d     15      2     0      

2 个答案:

答案 0 :(得分:3)

您的数据:

df1 <- read.table(
  text = 
    "plot   grass moss   rock    other     stuff  
    a      4      0     0       text      3
    b      2      2     0       text      4
    c      10     0     0       text      0
    d      3      1     0       text      9",
  header = TRUE
)

df2 <- read.table(
  text = 
    "Cover  value
    grass   5
    moss    2
    rock    3",
  header           = TRUE,
  stringsAsFactors = FALSE
)

(确保Cover是此解决方案的字符向量,而不是因素。)

一个简单的for循环可以解决这个问题:

df3 <- df1
for(i in seq_len(nrow(df2)))
{
  df3[, df2$Cover[i]] <- df2$value[i] * df1[, df2$Cover[i]]
}

答案 1 :(得分:0)

对于那些寻求 tidyverse 方法的人,以下也适用于使用新的 across()cur_column() 函数:

df1 %>% 
  mutate(across(.cols = c(grass, moss, rock),
                .fns = function(x){
                  x * (df2 %>% 
                         filter(Cover == cur_column()) %>% 
                         pull(value))
                }))