如何使用连续(顺序)索引替换数据框中的特定单元格值?

时间:2019-05-10 12:00:19

标签: r dataframe

我有两个尺寸相等的数据框。 一个在我需要索引的单元格中有一些值(即“ abc”)。其他具有所有不同的值。而且我需要用与“ abc”相同的索引替换其他数据框中的值。

示例:

df1 <- data.frame('1'=c('abc','bbb','rweq','dsaf','cxc','rwer','anc','ewr','yuje','gda'),
              '2'=c(NA,NA,'bbb','dsaf','rwer','dsaf','ewr','cxc','dsaf','cxc'),
              '3'=c(NA,NA,'dsaf','abc','bbb','cxc','yuje',NA,'ewr','anc'),
              '4'=c(NA,NA,'cxc',NA,'abc','anc',NA,NA,'yuje','rweq'),
              '5'=c(NA,NA,'anc',NA,'abc',NA,NA,NA,'rwer','rwer'),
              '6'=c(NA,NA,'rweq',NA,'dsaf',NA,NA,NA,'bbb','bbb'),
              '7'=c(NA,NA,'abc',NA,'ewr',NA,NA,NA,'abc','abc'),
              '8'=c(NA,NA,'abc',NA,'rweq',NA,NA,NA,'cxc','bbb'),
              '9'=c(NA,NA,NA,NA,'abc',NA,NA,NA,'anc',NA),
              '10'=c(NA,NA,NA,NA,'abc',NA,NA,NA,'rweq',NA))

df2 <- data.frame('1'=c('green','black','white','yelp','help','green','red','brown','green','crack'),
              '2'=c(NA,NA,'black','yelp','green','yelp','brown','help','yelp','help'),
              '3'=c(NA,NA,'yelp','green','black','help','green',NA,'brown','red'),
              '4'=c(NA,NA,'help',NA,'green','red',NA,NA,'green','white'),
              '5'=c(NA,NA,'red',NA,'green',NA,NA,NA,'green','green'),
              '6'=c(NA,NA,'white',NA,'yelp',NA,NA,NA,'black','black'),
              '7'=c(NA,NA,'green',NA,'brown',NA,NA,NA,'green','green'),
              '8'=c(NA,NA,'green',NA,'white',NA,NA,NA,'help','black'),
              '9'=c(NA,NA,NA,NA,'green',NA,NA,NA,'red',NA),
              '10'=c(NA,NA,NA,NA,'green',NA,NA,NA,'white',NA))

我可以找到'abc'的顺序索引,但它返回的是一个单精度的向量

which(df1 == 'abc')
#[1]  1 24 35 45 63 69 70 73 85 95

我不知道如何使用这种方法替换值

在预期用替换值“绿色”查看df2的输出中,仅在与df1中的值“ abc”相同的索引上。

但是请注意!! df2中的“绿色”值不仅与df1中的索引相同

2 个答案:

答案 0 :(得分:1)

我认为data.frame中的数据不能适当地解决您的问题。这带来了一些并发症。首先,数据帧中的每个变量(列)都是具有不同级别的一个因素!其次,您的代码正在对列表(data.frame)和一个因子(强制转换为原子向量)进行比较。 ==运算符的帮助功能表示 ..如果另一个是列表R试图将其强制转换为原子向量的类型。辅助功能还指出了因素比较中的特殊处理,它首先假定您正在比较代码正在执行的因子水平

我想您想先将相同尺寸的数据框转换为矩阵。如果您需要data.frame中的结果,请按照我在此处所示的方法将其转换回去,但要意识到因子水平可能已经改变。

# Starting with the values assigned to df1 and df2
  m1 <- as.matrix(df1)
  m2 <- as.matrix(df2)
  index <- which(m1 == "abc")
  m2[index] <- "abc"
  df2 <- as.data.frame(m2)

答案 1 :(得分:0)

这是一种方法。了解R中的* apply系列:我想这是该语言中最有用的一组功能,无论您打算做什么;)还知道data.frame是'list'类型的。

df1 <- lapply(df1, function(frame, pattern, replace){ # for each frame = column:
  matches <- which(pattern %in% frame)                # what are the matching indexes of the frame
  if(length(matches) > 0)                             # If there is at least one index matching,
    frame[matches] <- replace                         # give it the value you want
  return(frame)                                       # Commit your changes back to df1
}, pattern="abc", replace= "<whatYouWant>")           # don't forget this part: the needed arguments !