Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用与其他数据框中的列/行名称匹配的条件替换_R_Plyr - Fatal编程技术网

R 使用与其他数据框中的列/行名称匹配的条件替换

R 使用与其他数据框中的列/行名称匹配的条件替换,r,plyr,R,Plyr,我有两个数据帧: id <- c("a", "b", "c") a <- 0 b <- 0 c <- 0 df1 <- data.frame(id, a, b, c) id a b c 1 a 0 0 0 2 b 0 0 0 3 c 0 0 0 num <- c("a", "c", "c") partner <- c("b", "b", "a") value <- c("10", "20", "30") df2 <- data

我有两个数据帧:

id <- c("a", "b", "c")
a <- 0
b <- 0 
c <- 0
df1 <- data.frame(id, a, b, c)

  id a b c
1  a 0 0 0
2  b 0 0 0
3  c 0 0 0

num <- c("a", "c", "c")
partner <- c("b", "b", "a")
value <- c("10", "20", "30")
df2 <- data.frame(num, partner, value)

  num partner value
1   a       b    10
2   c       b    20
3   c       a    30
我可以用以下内容替换单个单元格:

df1$b[df1$id=="a"] <- ifelse(df2$num=="a" & df2$partner=="b", df2$value, 0)
要制作此文件:

  num    a  b
1   a <NA> 10
2   c   30 20
numab
1 a 10
2 c 30 20
但是,我确实需要所有可能的行/列组合,所有行/列组合都表示为零。有没有办法要求整形从另一个数据帧(如df1)获取行和列,或者在整形后我应该绑定这些行和列?

如果您想要替换(而不是整形),我认为一个简单的base R解决方案是:

idxs <- t(mapply(cbind, match(df2$num, df1$id), match(df2$partner, names(df1))))
df1[idxs] <- df2$value

df1
  id  a  b c
1  a  0 10 0
2  b  0  0 0
3  c 30 20 0

rowname(df1)
?您是否真的需要替换,或者您实际上只是想将
df2
重新塑造为
df.nice
格式?@Mike H.如果包含所有可能的行/列组合,则重新塑造是可行的。我现在就来试试,thanks@hoho如果要使用“重塑”,请遵循Henrik链接副本中的解决方案。这将需要一些设置工作,尽管需要重新调整因子。类似这样的解决方案会奏效:
df2$num或者,您可以尝试一个非重塑解决方案,如我在下面发布的那样
  num    a  b
1   a <NA> 10
2   c   30 20
idxs <- t(mapply(cbind, match(df2$num, df1$id), match(df2$partner, names(df1))))
df1[idxs] <- df2$value

df1
  id  a  b c
1  a  0 10 0
2  b  0  0 0
3  c 30 20 0
df2 <- data.frame(num, partner, value, stringsAsFactors = F)
df1 <- data.frame(id, a, b, c, stringsAsFactors = F)