将矢量的一部分替换为相同data.frame的另一个矢量的一部分

时间:2014-03-11 17:22:45

标签: r vector replace dataframe character

我想用article.x的第4行到第6行替换article.y的第4到第6行 我确定这是一个非常简单的解决方案,但我还没有设法找到它。 我的data.frame

no <- c(1, 4, 6, 3, 2, 5)
article.y <- c("one", "two", "three", "four", "five", "six")
article.x <- c("apple", "peach", "plum", "berry", "cherry", "banana")

mydf <- data.frame(no, article.y, article.x)
mydf

#  no article.y article.x
# 1 1       one     apple
# 2 4       two     peach
# 3 6     three      plum
# 4 3      four     berry
# 5 2      five    cherry
# 6 5       six    banana

输出应如下所示:

#   no article.y article.x 
#  1 1       one     apple
#  2 4       two     peach
#  3 6     three      plum
#  4 3     berry     berry
#  5 2    cherry    cherry
#  6 5    banana    banana

我绝望的方法之一:

mydf$article.y[4:6] <- mydf$article.x[4:6]

1 个答案:

答案 0 :(得分:1)

我猜你因为正在处理各种因素而遇到问题。首先将相关列转换为character,然后您可以使用您的方法或类似的变体:

mydf[-1] <- lapply(mydf[-1], as.character)
mydf[4:6, 2] <- mydf[4:6, 3]
mydf
#   no article.y article.x
# 1  1       one     apple
# 2  4       two     peach
# 3  6     three      plum
# 4  3     berry     berry
# 5  2    cherry    cherry
# 6  5    banana    banana