使用另一个数据帧的一行中的值替换一个数据帧的一列中的所有值(按行名和列名匹配) [英] Replace all values in a column of one dataframe using values in a row of another dataframe (matching by row name and column name)

查看:39
本文介绍了使用另一个数据帧的一行中的值替换一个数据帧的一列中的所有值(按行名和列名匹配)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,它是在不同位置发现的物种的存在缺失矩阵(1 表示存在,0 不存在),如下所示:

I have a dataframe which is a presence absence matrix of species found in different locations (1 indicates presence, 0 absence) like so:

df1<-data.frame(replicate(5,sample(0:1,5,rep=TRUE)))
row.names(df1)<-c("location.1","location.2","location.3","location.4","location.5")
names(df1)<-c("species.1","species.2","species.3","species.4","species.5") 

           species.1 species.2 species.3 species.4 species.5
location.1         0         1         0         1         1
location.2         1         0         0         1         0
location.3         0         0         1         0         0
location.4         1         0         1         0         1
location.5         0         0         1         0         0

我有第二个数据框,其中包含每个物种的值,如下所示:

I have a second dataframe which has values for each species, like so:

df2<-c(2,4,6,8,10)
df2<-as.matrix(df2)
row.names(df2)<-c("species.1","species.2","species.3","species.4","species.5")

          [,1]
species.1    2
species.2    4
species.3    6
species.4    8
species.5   10

我想将第一个数据框中的所有 1 逐列替换为第二个数据框中的匹配值(基于物种名称).生产这个:

I would like to replace all 1s in the first dataframe, on a column by column basis, with the matching value in the second dataframe, based on the species names. Producing this:

           species.1 species.2 species.3 species.4 species.5
location.1         0         4         0         8        10 
location.2         2         0         0         8         0
location.3         0         0         6         0         0
location.4         2         0         6         0        10
location.5         0         0         6         0         0

我不知道我会怎么做,而且在网上找不到任何类似的例子.

I have no idea how I'd go about doing this though, and can't find any similar examples online.

有人有什么建议吗?

推荐答案

我们可以通过以下选项之一来做到这一点

We can do this by one of the options below

 df1*df2[,1][col(df1)]

在这里,我们将第一个数据集与复制的 'df2' 的第一列相乘以使长度相同

Here, we multiply the first dataset with the first column of 'df2' replicated to make the lengths same

或者另一个选项是 sweep,它有 MARGINSTATSFUN 参数来应用函数列的相应元素(MARGIN = 1 对行进行处理)

Or another option is sweep which has the MARGIN, STATS and FUN argument to apply the function on corresponding elements of column (MARGIN = 1 does on rows)

 sweep(df1, 2, df2[,1], "*")

<小时>

或者我们可以使用 mapply 遍历列并乘以向量 'df2[,1]` 的相应元素


Or we can use mapply to loop over the columns and multiply by the corresponding elements of the vector 'df2[,1]`

 mapply("*", df1, df2[,1])

这篇关于使用另一个数据帧的一行中的值替换一个数据帧的一列中的所有值(按行名和列名匹配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆