cptn
cptn

Reputation: 703

Replace part of a vector with a part of another vector of the same data.frame

i want to replace rows 4 to 6 of article.y with row 4 to 6 of article.x i'm sure there's a very simple solution, but i just haven't managed to find it. my 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

the output should look like this:

#   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

one of my desperate approaches:

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

Upvotes: 1

Views: 47

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

I'm guessing that you're just running into problems because you are working with factors. Convert the relevant columns to character first, and then you can use your approach or similar variants:

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

Upvotes: 1

Related Questions