使用另一个数据帧的行中的值替换一个数据帧的列中的所有值(按行名称列名称匹配),替换为字符

标签 r dataframe

这与帖子“Replace all values in a column of one dataframe using values in a row of another dataframe (matching by row name and column name)”非常相似

除了我的替换要求是将那些(“1”)替换为该列所在的列的名称。

示例设置

df1<-data.frame(replicate(5,sample(0:1,5,rep=TRUE)))
row.names(df1)<-c("hootsuite","foodtank","FarmsNews","agchat","TysonFoods")
names(df1)<-c("food","agvocate","editor","gmo","ag")

           food agvocate editor gmo ag
hootsuite     1        1      0   0  1
foodtank      1        1      0   0  1
FarmsNews     1        0      1   0  1
agchat        0        0      0   0  1
TysonFoods    1        0      1   1  0

会变成

                food    agvocate    editor gmo      ag
hootsuite       food    agvocate    0       0       ag
foodtank        food    agvocate    0       0       ag
FarmsNews       food    0           editor  0       ag
agchat          0       0           0       0       ag
TysonFoods      food    0           editor  gmo     0

similar post中的解决方案

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

(使用下面定义的 df2)

df2<-c("food","agvocate","editor","gmo","ag")
df2<-as.matrix(df2)
row.names(df2)<-c("food","agvocate","editor","gmo","ag") 

给出错误“FUN(左,右)中的错误:二元运算符的非数字参数”,这意味着矩阵乘法实际上不适用于字符;)

那么我应该采取什么方法?

最佳答案

我们可以使用Map替换相应的列,其值为列名为1的值

df1[] <- Map(function(x, y) replace(x, x==1, y), df1, names(df1))
df1
#           food agvocate editor gmo ag
#hootsuite  food agvocate      0   0 ag
#foodtank   food agvocate      0   0 ag
#FarmsNews  food        0 editor   0 ag
#agchat        0        0      0   0 ag
#TysonFoods food        0 editor gmo  0
<小时/>

或者使用逻辑矩阵进行子集化和分配

df1[df1==1] <- names(df1)[col(df1)][df1==1]

关于使用另一个数据帧的行中的值替换一个数据帧的列中的所有值(按行名称列名称匹配),替换为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805026/

相关文章:

javascript - 部署服务器和Javascript API,大数据返回 "Project in Use"

python - 如何在Python中格式化具有多列但单行的数据框?

Python绘图y轴平均标签不会显示并且日期都很拥挤

rChart nPlot - 更新 yAxis 标签

r - ggplot2 未正确保存 geom_raster() 绘图

regex - 使用 r 删除希伯来语 "niqqud"

python - 如何获取作为字典的数据帧的列的值

python - 如何将 pandas 数据框日期时间列转换为 int?

python - 来自 csv 的 Pandas Dataframe 显示不正确

r - 为什么这些表达不相同?