【问题标题】:Replace part of a vector with a part of another vector of the same data.frame用相同data.frame的另一个向量的一部分替换向量的一部分
【发布时间】:2014-04-15 10:30:37
【问题描述】:

我想用 article.x 的第 4 到 6 行替换 article.y 的第 4 到 6 行 我敢肯定有一个非常简单的解决方案,但我只是没有设法找到它。 我的数据框架

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]

【问题讨论】:

  • 如果您使用stringsAsFactors=FALSE 创建您的data.frame,它应该可以工作:mydf &lt;- data.frame(no, article.y, article.x, stringsAsFactors=FALSE)

标签: r vector replace dataframe character


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2015-07-07
    • 2021-07-13
    相关资源
    最近更新 更多