这与帖子" 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
中的解决方案
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")
给出错误&#34; FUN中的错误(左,右):二元运算符&#34; 的非数字参数,意味着矩阵乘法实际上不适用于字符;)
所以我应该采取的方法是什么?
答案 0 :(得分:3)
我们可以使用OnClickListener
到Map
相应列,其值为1,列名为
replace
或使用逻辑矩阵进行子集化和分配
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
答案 1 :(得分:2)
使用purrr
包的解决方案。 map2_dfc
可以使用函数循环遍历两个列表或向量(在本例中为df1
和names(df1)
)。它还可以将输出绑定为数据帧。
set.seed(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")
library(purrr)
df2 <- map2_dfc(df1, names(df1), function(x, y){
x[x %in% 1] <- y
return(x)
})
df2
# # A tibble: 5 x 5
# food agvocate editor gmo ag
# <chr> <chr> <chr> <chr> <chr>
# 1 0 agvocate 0 0 ag
# 2 0 agvocate 0 gmo 0
# 3 food agvocate editor gmo ag
# 4 food agvocate 0 0 0
# 5 0 0 editor gmo 0